header file help!

Started by
1 comment, last by R67en 20 years, 4 months ago
I have a header file that contains all my globals and prototypes. The source file is getting really large, and is now a big pain to sort through to find what Im looking to modify. I want to split my source file into 2 or more files. Doing so will require accessing the global variables in the header file by both source files. Can I do this? I tried doing so, and got 76 errors like the following: error LNK2005: _WinMain@16 already defined in WGP11GameStates.obj I get one of these for each variable and prototype in my header. In the header, I have the following: #ifndef WGP11MAIN #define WGP11MAIN //code #endif I thought this was supposed to ensure that the file was compiled only once? Please give me some help, thanks.
Advertisement
well, here''s the thing --

you can''t actually declare the variables in your header file if you''re going to include it in more than one place. this is a general rule, since most of the time a header file will be included by more than one source file.

you need to put the variable declaration in a source file (.cpp)
however, you need to let the files that include the header know that there is a global variable somewhere for them to use.

do this using the extern keyword.

for example, in your SomeHeader.h file:
#ifndef SOMEHEADER_H
#define SOMEHEADER_H

extern Bool gSystemStarted;

#endif

in your Globals.cpp file

#include "SomeHeader.h"

Bool gSystemStarted = false

in your Startup.cpp file
#include "SomeHeader.h"

void StartSystem()
{
gSystemStarted = true;
}

this is similar to how you make function prototypes to tell the various .cpp files that some function is out there for them to call.. but you but the function definition in the header file.

(i''m sorry -- i mix up the "declaration" and "definition" words a lot. but conceptually, i hope you''re with me. the line where you actually write "Bool gSystemStarted" has to be in source, and only once for the whole build.)

hope that helps.
so the ifndef guards, by the way, only make sure that the header file is included once per .cpp file. but if you have multiple cpp files that use the header, each of them will include the .h file, because they''re different passes through the compiler. basically.

This topic is closed to new replies.

Advertisement