If you have a variable, structure, or another data type that you want to define in one source file and access in another source file, you can do so using an extern declaration.
The best way to do this is to create a header file(s) that can hold all the declarations and that can be included in each source file that needs to access that particular variable. A variable is said to be defined when the compiler allocates the storage for the variable. A variable is said to be declared when the compiler knows of its data type, and that the variable exists, but has not allocated storage to it.
Let’s say you have a volatile int variable called IOstate that must be accessible anywhere in the program. The file main.c, for example, might define the variable:
Now, create a header file (say vars.h) and declare the IOstate as:
The declaration must include any qualifiers used in the definition. Now this header file can be included to C source files that need to access this variable:
If vars.h was shared between file_1.c and file_2.c.
To prevent duplicate definitions and declarations, guards may be applies as follows in vars.h:
file_1.c and file_2.c may contain
in order to access the shared symbols and variables.
If vars.h is stored in the project parent directory, you don’t need to include the paths to it under the compiler build options.
You should also include the header file into the source file that actually defines the variable. This makes sure that the definition in the C source file is checked against the declaration in the header file. If there is any inconsistency, the compiler will send out a warning and the user should make the declaration and the definition consistent.
You should never place definitions in a header file, other than defining types (typedefs) or structure/union tags, etc.
For example, the definition of count is as:
This definition should not be put in the header file; it should ideally be put into the C source file.