Home >Backend Development >C++ >How to Efficiently Manage Global Variables Across Multiple Source Files?
When working with multiple source files in a programming project, it becomes essential to efficiently access and share global variables among them. Let's explore the best practices for achieving this:
The recommended approach is to declare the global variable as 'extern' within a header file that is included by all the source files requiring access to it. Additionally, the variable should be defined in only one of the source files.
For instance, consider the following header file, 'common.h':
extern int global;
In 'source1.cpp':
#include "common.h" // Define global variable int global = 42; int function(); int main() { // Access global variable global = 42; function(); return 0; }
In 'source2.cpp':
#include "common.h" int function() { // Access global variable if (global == 42) { return 42; } return 0; }
By declaring the variable as 'extern' in the header file and defining it in 'source1.cpp,' all source files can access and manipulate the same global variable. This method ensures consistency and prevents multiple definitions.
The above is the detailed content of How to Efficiently Manage Global Variables Across Multiple Source Files?. For more information, please follow other related articles on the PHP Chinese website!