Sometimes the source code for a C program is contained in more than one
text file. If this is the case, then it may be necessary to use
variables that are defined in another file. You can use a global
variable in files other than the one in which it is defined by
redeclaring it, prefixed by the extern specifier, in the other files.
File main.cFile secondary.c
#include <stdio.h>
int my_var;
int main()
{
extern int my_var; void print_value()
{
my_var = 500; printf("my_var = %d\n", my_var);
print_value(); }
exit (0);
}
In this example, the variable my_var is created in the file
secondary.c, assigned a value in the file main.c, and
printed out in the function print_value, which is defined in the
file secondary.c, but called from the file
main.c.
See Compiling multiple files, for information on how to compile a
program whose source code is split among multiple files. For this
example, you can simply type the command gcc -o testprog main.c
secondary.c, and run the program with ./testprog.