Ok, could you tell me why this #ifndef structure is not working correctly?

Started by
3 comments, last by QBRADQ 22 years, 6 months ago
#ifndef GLOBALS_H #define GLOBALS_H bool bGameLoop; #endif //GLOBALS_H The above code within the #ifndef structure happens every time I call the header, and I don''t know why! This seems to happen if I am declairing objects or variables, but works just fine if I am declairing a funciton or a class, or I am definning something. Any thoughts?
Tell him about the twinky...
Advertisement
Try #ifndef _H_GLOBALS
put "bool bGameLoop;" it its own source file, and put "extern bool bGameLoop;" in its place.

[Resist Windows XP''s Invasive Production Activation Technology!]
GLOBALS_H is my own definition, and changing that should have no effect. (Latter tested, and it did not)

Null and Void: Your solution worked. Thank you! But this does make me wonder, should the compiler behaive like that?
In a word: yes.

the #ifndef thing just stops you including the same file more than once into the same .cpp file. If you have multiple .cpp files, it will be included into each one once.

Every time the compiler sees "bool bGameLoop", it allocates space for bGameLoop, but then when you try and link, the linker will see that you''ve allocated space for bGameLoop in every file that included your globals.h. It won''t know which one you actually want to use, and generates an error.

If you declare bGameLoop "extern", that tells the compiler that "bGameLoop" is a variable, but that it''s actually defined somewhere else. When you link, the linker only sees the space allocated for one bGameLoop (the one you didn''t put extern on, in the .cpp file), and all the .cpp files that used the "extern" version will point to that one.

codeka.com - Just click it.

This topic is closed to new replies.

Advertisement