C extern
C extern
is a keyword in the C programming language that is used to declare a variable or function that is defined in another source file. When a variable or function is declared as extern
, it means that the actual definition of that variable or function is located in a different source file. The extern
keyword is typically used when you want to use a variable or function that is defined in another file, without redefining it.
To declare an extern
variable, you use the extern
keyword followed by the data type and the variable name. For example:
extern int x;
This declares an extern
variable named x
of type int
. It tells the compiler that the actual definition of x
is located in another source file.
To declare an extern
function, you use the extern
keyword followed by the return type, the function name, and the parameter list (if any). For example:
extern int add(int a, int b);
This declares an extern
function named add
that takes two int
parameters and returns an int
. It tells the compiler that the actual definition of the add
function is located in another source file.
When you use an extern
variable or function in your code, the compiler will look for its actual definition in other source files during the linking phase. If the compiler cannot find the definition, it will result in a linker error.
It's important to note that the extern
keyword is not required if the variable or function is defined in the same source file. In that case, you can simply declare the variable or function without the extern
keyword.
Using the extern
keyword allows you to separate your code into multiple source files and reuse variables and functions across different files. It's commonly used in large projects to improve code modularity and organization.