Advertisement

Question on Initialization in Headers

Started by June 03, 2000 10:21 PM
6 comments, last by Peddler 24 years, 6 months ago
Hey, Ok I have a header file game.h which controls a number of cpp''s which each hold various game related functions. Now there is one variable I need the place in the game.h file so that it is global to all the game cpp''s..but..I also need to initialize it in the header. How do I go about doing this so it is inited only once as I get errors because every cpp is trying to initialize the variable. ::this is the object list I need to init in the global header file..any ideas on how I can go about doing this so that it is inited globaly only once? DECLARE BList slBlockDrown(100); Thanks! -Tim Yarosh
To declare a global variable in a header file that will be visible to every other source file, you''ll need to declare it extern as in
extern int count;

you must then declare a global variable called count in one of your source files. When you''re initialising the variable there, you can then initialise it to zero.

as in int count = 0;

Hope this is what you''re looking for



========================================================
If something sounds stupid but works, it's not stupid
==========================================In a team, you either lead, follow or GET OUT OF THE WAY.
Advertisement
Yeah, I have it check to set to extern...and...most of the variables, I do..do just what you said. But I with this list I can''t declare it in the header..and...then intialize it in a source file, I have to do it all in the header.

Thanks for the reply though.

I assume I could wrap it in a class and have it inited in the constructer, but I''d like to be able to do it in the header if at all possible.
Just why do you have to initialize it in the header file? Wrapping it in a class seems like too much for this situation, in my opinion...
Because the constructor for the BList object needs the number of objects to make space for. The object itself won''t initialize if there isn''t a number::

BList slBlockDrown(number_needed_here);




I get why you need to initialize it, I just don''t know why that has to be in the header.. I can''t think of a situation where declaring and initializing it in a cpp file, then declaring it extern in a header wouldn''t be enough...
Advertisement
What I would do is define it in the Header, then in each of the .CPP files put extern. It should work. Thats how I do it in my code
If you haven't already done so, you could also try watching for multiple inclusions of the header by doing this:

#ifndef GAME_H
#define GAME_H

... rest of file

#endif


- Daniel
my homepage

Edited by - deakin on June 5, 2000 6:02:02 AM
- DanielMy homepage

This topic is closed to new replies.

Advertisement