i have a header file which contains a random number generator

here is the code:

#include <cstdlib>
#include <time.h>

#ifndef RANDOM_H

struct rand_var{
	int x,y;
}Rand_var;


static int rand_gen()
{
	srand ((unsigned)time(NULL));
	extern int random;
	random = rand() % (Rand_var.x-Rand_var.y+1) + Rand_var.x;
}
#endif /* random.h */

you will probably com-plain about the struct, and that i should just put the declaration in the static int, or just not in there at all.

anyways, the problem i'm having is when i try to intialize it in this code:

#include <iostream>
#include <Windows.h>
#include <conio.h>

#include "random.h"

struct enemies
{
	bool alway_app;
	bool cote_app;
	bool alexF_app;
}enemy;

using namespace std;

int main()
{
	extern int random;
	int i;
	do
	{
		for(i = 0; i>=100; random)
			if (i == 1 || i == 2 || i == 3)
				break;
			else continue;
	}while(i = 0);

	if (i == 1)
		enemy.alway_app = true;
	else if (i == 2)
		enemy.cote_app = true;
	else enemy.alexF_app = true;

	if(enemy.alway_app = true)
		cout << "Kaleb Alway Appeared!\n\n";
	if(enemy.cote_app = true)
		cout << "Dylan Cote Has Appeared\n\n";
	if(enemy.alexF_app = true)
		cout << "Alex Frankland has appeared\n\n";
	cout << random << "\n\n";
	cout << random << "\n\n";
	Sleep(0500);
	return 0;
}

it keeps on giving me LNK2001 and LNK1120 errors where it says "EXTERN INT RANDOM". so i must have declared them wrong.

anyways, how do i declare it properly?

The error comes from the fact that declaring a variable as extern does not "declare" the variable, it simply tells the compiler that there is a global variable with that name. Somewhere, you need to have a global variable with that name. You don't have that anywhere. You could just put a "int random = 0;" somewhere in the global scope (outside any function body). However, I really don't get the point of your implementation, the random variable will never change because rand_gen() is never called.

This is probably the implementation that makes more sense:

#include <cstdlib>
#include <ctime> //use ctime, not time.h
 
#ifndef RANDOM_H

struct rand_var{
	int x,y;
}Rand_var;

struct Rand_seeder { Rand_seeder() { std::srand((unsigned)std::time(NULL)); }; };

inline int rand_gen() //use the inline keyword here, not static.
{
	static Rand_seeder rs; //will seed the random number gen. only once.
	return rand() % (Rand_var.x-Rand_var.y+1) + Rand_var.x; //use a return value.
}
#endif /* random.h */

Then you call rand_gen every time you need a new random number in that range that you have (also, having this range thing as a global variable is pretty bad too).

oh. no wonder i kept getting errors. it was originally in part of the CPP file but it kept returning 42.

anyways thanks for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.