I have two source files that need to access a common variable. What is the best way to do this? e.g.:
source1.cpp:
int global; int function(); int main() { global=42; function(); return 0; }
source2.cpp:
int function() { if(global==42) return 42; return 0; }
Should the declaration of the variable global be static, extern, or should it be in a header file included by both files, etc?
You should achieve that the compiler gets the same extern declaration for each compilation unit, that needs the declaration. When you spread the externs over all files that needs extern access to the variable, function, ... it is difficult to keep them in sync. That's why: don't declare extern in the consuming .
A global variable is accessible to all functions in every source file where it is declared. To avoid problems: Initialization — if a global variable is declared in more than one source file in a library, it should be initialized in only one place or you will get a compiler error.
Every C file that wants to use a global variable declared in another file must either #include the appropriate header file or have its own declaration of the variable. Have the variable declared for real in one file only.
The global variable should be declared extern
in a header file included by both source files, and then defined in only one of those source files:
common.h
extern int global;
source1.cpp
#include "common.h" int global; int function(); int main() { global=42; function(); return 0; }
source2.cpp
#include "common.h" int function() { if(global==42) return 42; return 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With