Global variables have been present in C since the very beginning as a means of storing data accessible in all functions of the program. They allow organizing the exchange of information between different parts of the code without explicitly passing values through function parameters. Such variables are stored in a separate memory area and exist for the entire lifespan of the program.
Excessive and uncontrolled use of global variables leads to maintenance problems in the code, complicating error tracing and increasing the risks of name conflicts. In large projects, it is difficult to understand where modifications to globally accessible data occur, making debugging more challenging. Additionally, incorrect declaration of global variables in different files (modules) can lead to linker errors and data duplication.
The optimal practice is to explicitly declare global variables in one .c file and export their prototypes with the extern keyword in header .h files. This creates a single storage location, and the compiler prevents duplication. To minimize global variables, static variables with file scope are used. Excessive use of global state is replaced with data structures that are passed between functions.
Example code:
// file.h #ifndef FILE_H #define FILE_H extern int global_counter; #endif // file.c #include "file.h" int global_counter = 0; // main.c #include "file.h" #include <stdio.h> int main() { global_counter++; printf("%d\n", global_counter); return 0; }
Key features:
extern is used.Can a global variable be declared static? How will it differ from a regular global variable?
Yes, a global variable declared with the static keyword will only be visible within the file in which it was declared. It still lives for the duration of the program, but another compilation (another .c file) will not be able to access it. This is used for encapsulating data at the file level.
Is it necessary to use extern to access a global variable from another file?
Yes, if you want to access a global variable defined in another module, you must declare it with the extern keyword (usually in the header file). Otherwise, the compiler will assume that you are redefining the variable.
// a.c int global_var = 1; // b.c extern int global_var;
Will the following code work?
// a.c int var; // b.c int var;
No, such code will lead to a linker error because the variable is defined twice. The definition of a global variable should be unique, and extern should be used for access.
A developer places configuration parameters in global variables without access restrictions:
Pros:
Cons:
Global variables are defined only in one file, accessed through extern, and strictly documented. In other cases, a static file scope or parameter structuring is used:
Pros:
Cons: