The extern keyword in C plays a crucial role in managing global variables. It enables you to declare the existence of a global variable in multiple source files while defining it only once.
The extern keyword informs the compiler about the existence of a global variable. It doesn't provide a definition but simply declares its name and type. By using extern, you can access the variable in other source files without redefining it.
Consider the following example:
header.h:
#ifndef HEADER_H #define HEADER_H extern int global_x; void print_global_x(); #endif
source1.cpp:
#include "header.h" // Define global_x here int global_x = 5; int main() { print_global_x(); }
source2.cpp:
#include "header.h" void print_global_x() { std::cout << global_x << std::endl; }
In this example, global_x is declared in header.h using extern, making it known to both source1.cpp and source2.cpp. However, it's defined only in source1.cpp, ensuring that it's available for use in both source files.
The above is the detailed content of When Should You Use the `extern` Keyword for Global Variables in C ?. For more information, please follow other related articles on the PHP Chinese website!