What is the extern Keyword?
In C, the extern keyword is used to declare a global variable or function that can be shared across multiple files. It informs the compiler that the definition of the variable or function resides in another file. This allows you to define the global variable or function in one file and use it in other files without redefining it.
How to Use the extern Keyword
The extern keyword is primarily used in two scenarios:
- Declaring Global Variables: When a global variable is defined in one file and needs to be accessed in other files, you can declare it using the
externkeyword in those other files. - Declaring Functions: Function declarations are typically in header files, while definitions are in source files. Using
externallows sharing access to the same function across multiple source files.
Example
Suppose there are two files: main.c and helper.c.
In helper.c, a global variable and a function are defined:
c// helper.c #include<stdio.h> int count = 5; // Global variable definition void print_count() { printf("Count is %d\n", count); }
In main.c, we want to use the global variable and function defined in helper.c:
c// main.c #include<stdio.h> extern int count; // Declare global variable using extern extern void print_count(); // Declare function using extern int main() { print_count(); count = 10; print_count(); return 0; }
Important Notes
- When using
extern, ensure that the variable or function has been defined somewhere; otherwise, a linking error will occur. - For global variables, if
externis used without any definition, the compiler will not allocate memory for it. externis only for declaration, not for definition. Definition creates storage space, while declaration informs the compiler of its existence.
Through the above examples and explanations, it is evident that the extern keyword is important and correctly used for managing global variables and functions in multi-file projects. This approach helps maintain code modularity and ease of management.