Accessing Global Variables Across Multiple Source Files
In the given scenario, you have two source files that require access to a shared variable named global. Determining the most efficient way to achieve this is crucial.
The solution lies in declaring global as extern within a header file that both source files include. This approach ensures that the variable is visible to all source files but defined in only one.
In the header file (common.h):
extern int global;
In source1.cpp:
#include "common.h" int global; // Define global in only one source file int function(); int main() { global = 42; function(); return 0; }
In source2.cpp:
#include "common.h" int function() { if (global == 42) return 42; return 0; }
By utilizing this approach, both source1.cpp and source2.cpp can access the shared variable global without creating compilation errors or unexpected behavior.
The above is the detailed content of How Can I Efficiently Share Global Variables Across Multiple Source Files?. For more information, please follow other related articles on the PHP Chinese website!