Quote:
Originally Posted by weaknessforcats
Gobal variables share the same scope regardless of whether or not they are defined in a library. When they have the same name your build dies with duplicate definitions.
All of the variables reside in a portion of memory rerserved for global variables. That is, they are not on the stack nor are they on the heap.
To be on the stack, the variable must be defined inside a function. To be on the heap, the variable must be allocated from inside a function.
The global can be defined as static but this just restricts the problem to the one file that defines the global. A static global variable can use used only in the file that defines it.
One solution is to not use any global variables in your code that are not in a namespace. If you code this way:
-
namespace jazi
-
{
-
int thedata;
-
}
-
this variable is identified as jazi::thedata whereas a variable outside the name space is just thedata. At least that would separate your stuff from the library.
I am assuming you are coding in C++ because if this is C, you are dead. With C, you have to a) make all of your global variables static and pack all your code into one source file, or b) rename all of your global variables so they are different from the library's and hope no one reuses one of your names.
Global variables are among the worst code practices known to man.
I really appreciate your feedback and it makes a lot of sense. However, here is my situation.
I am using an open source code. I really do not want to make changes to the code at all. If possible then I will rather do the minimum. So the namespace thing you mentioned above makes a lot of sense and I thought about it but it will require a lot of changes into the current version. Here is what I have and here where the issue reside.
There are two headers in this package; globs.h and exts.h. The globs.h contains the declaration and initialization of this variable as
//globs.h
int thedata=0;
This header is included by ONE source code that have a function which upload the data from the files into these variables.
The second header exts.h is a mirror of the globs.h except the word "extern" added to each global variables in globs.h
//exts.h
extern int thedata;
This file is included by all the other functions (source files).
Now, I thought if I get rid of the "extern" word from the exts.h then this will work "stupid assumption" it fails so I thought of getting rid of the whole exts.h and include the globs.h instead but I got the duplication definitions issue as you mentioned above.
Is there a quick fix to this problem besides the one you mentioned above.
Best regards,