Home >Backend Development >C++ >How to Share Global Variables Between Multiple C/C Files?
Accessing Global Variables Across Multiple Files in C/C
When working with multiple source files in a C/C program, it is often necessary to share global variables between them. This can be achieved through various methods, including static and extern declarations or using a header file.
Consider the example provided:
source1.cpp:
int global; int function(); int main() { global = 42; function(); return 0; }
source2.cpp:
int function() { if (global == 42) return 42; return 0; }
Solution 1: Header File with extern
The preferred approach is to declare the global variable extern in a header file included by both source files:
common.h:
extern int global;
source1.cpp:
#include "common.h" int global; // Only define it in one file int function(); int main() { global = 42; function(); return 0; }
source2.cpp:
#include "common.h" int function() { if (global == 42) return 42; return 0; }
This ensures that the declaration of global is visible to both source files, but only one definition of it is present (in source1.cpp). The extern keyword specifies that the variable is declared elsewhere.
The above is the detailed content of How to Share Global Variables Between Multiple C/C Files?. For more information, please follow other related articles on the PHP Chinese website!