Managing Global Variables Across Multiple Files
Introduction
Access to common variables between source files is an essential aspect of program design. This article examines the optimal approaches to declare and access global variables within multiple files.
Best Practice
To declare a global variable accessible across multiple files, the following steps should be followed:
Header File Declaration: Declare the global variable as extern in a header file that both source files include.
//common.h extern int global;
Source File Definition: Define the global variable in only one of the source files. The file that defines the variable must not include the extern keyword.
//source1.cpp #include "common.h" int global = 42;
Alternative Approaches
While the recommended approach is to use an extern declaration and a single definition, there are alternative methods that are less desirable:
Example Implementation
Consider the following example:
//source1.cpp #include "common.h" int function(); int main() { global = 42; function(); return 0; } //source2.cpp #include "common.h" int function() { if (global == 42) return 42; return 0; }
By following the best practice of using an extern declaration and a single definition, both source files can share the global variable global effectively.
The above is the detailed content of How to Properly Manage Global Variables Across Multiple Source Files?. For more information, please follow other related articles on the PHP Chinese website!