Quote:
Originally Posted by javan
lacking the keyword "const". Once I introduced this keyword in front of all of them the compilation was successful because they were all inlined and referenced only once in the code.
What is happening is not what you think.
Each time a header file is included, its contents are processed. If you create variables, then each time you include the header, the variables are created again. Hence redefinition at the compiler level.
So, you do the #ifndef and the errors from the compiler go away only to be replaced by redefinition errors from the linker. This is caused by including the header file in multiple source files. The compiler sees only one file. The linker sees them all.
So, you add
const and all the errors go away. Unfortunately, what does not go away are all the variables. They have still been multiply created but the const tells the linker they can only be used in the file where they were defined.
So, if you have 5000 files in your program that include this header you have 5000 sets of variables.
Solution: Do not create variables in header files.
Header files are for declarations not definitions. A declaration says a thing exists. A definition uses the declaration to create the object.
What you should do is:
In the header, declare the variables as extern. That says the variables are in another file and are sharable (external linkage). LIke this:
-
//header.h
-
extern const int MAX;
-
extern const in MIN;
-
Then in
one source file, create the variables:
-
//app.cpp
-
extern const int MAX = 100;
-
extern const int MIN = -100;
-
Normally, constants have internal linkage so they are not sharable in other files. That is the default when you create them. The example above just overrides the default and makes the constant sharable.
Later, you can learn to not use global variables at all. However, one thing at a time.