If I don't put the extern in the header file then, I get a bunch of these errors:
abc1.obj : Error LNK2005: "bool myBool" already defined in abcN.obj
abc2.obj : ......same.....
abc1.exe : fatal error LNK1169: one or more multiply defined symbols found
These are very large files....and a large number of files as well. I am using VS2005.
To make it slightly more elaborate:
Constants Header File 1 : ABC1.h
#ifndef ABC1_H
#define ABC1_H
#define CONST_A "aa_ab"
......bunch of constant definitions
bool myBool;
#endif
#include "ABC1.h"
#include "ABC2.h"
#include <fstream>
....bunch of include files
class ABC3
{
int var1;
int var2;
std::map....
std:: ofstream.....
public:
ABC3(std::map..., std::ofstream....)
int startabc3func1();
int func2();
};
#endif
CPP file 1 - MAIN FILE - references/calls all other files : ABC2.cpp
#include <...>
#include "ABC2.h"
using namespace std;
extern int main(int argc, char *argv[])
{
char *varA1 = NULL;
..bunch of variable definitions
if (varA1 = NULL)
{
myBool = false
}
....
ABC3.startabc3func1();
return...
}
Second, why does your int main() have an extern preceding it?
Third, eliminate every instance of extern in your program. You don't need it unless you decide to omit the header files.
extern is used when you want to pass a note to the compiler and later linker that something is declared and/or defined in another C++ file and later object file.
Fourth, you do realize that #include "ABC1.h" is redundant when you have #include "ABC2.h"?
There's probably something in Fifth,, but I haven't found it yet.
This is one of the reasons why global variables are bad. Declaring it in a header file and including that in multilple source files results in the error that you're getting about the multiple definitions.
I think this is a good time to recommend the Singleton Pattern1. Here's a quick, untested, mock-up:
1 Note that this approach is not ideal, either. It would be best to determine "who" owns myBool and try to avoid all of this just to support a global variable.
I guess 2 questions:
1. If I include myBool as a part of the class - would multiple source files be able to access this flag ? One source file sets the flag based on a certain condition and the second source file executes a logic based on what the flag is set to ?
After thinking about why the example above should work, I'm starting to suspect that if you have an extern declaration in a header file and a single definition in a source file that the symbol would still obey the one definition rule and be accessible... All you need is external linkage for myBool. I beleive that the extern keyword is telling the compiler that treat that line as a declaration only--meaning that you would need a separate definition. Did you try adding bool myBool; in the cpp file with everything else like the first post?
I don't think that's quite what you're after. I think you want it to have its own source file and just include the header file in the other two source files.