If you have a variable (or structure, or other 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) which can hold all the declarations and which can be included into each source file that need to access that particular variable. Variable is said to be defined when compiler allocates the storage for the variable. 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:
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 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, compiler will warn about it, 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, 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.
Microchip Technology acquires Atmel