Here's file1.c:
// A global variable in this file: #include < stdio.h > int i; // A global variable from another file: extern int j; int main () { i = 5; // Access the file variable, as usual. printf ("i = %d\n", i); j = 6; // Access the other file's variable. printf ("j = %d\n", j); }
j is declared in file2.c:
#include < stdio.h > int j;
To create an executable executablename from the two files file1.c and file2.c you'll need to:
gcc -o executablename file1.c file2.c (or) gcc -o executablename file2.c file1.c
Notes:
Function access works similarly: You can define a function to be extern by placing the word extern in its prototype in this file.
It is good practice to create function prototypes for all your functions in each file as follows:
Large C projects use a makefile which facilitates specification of compilation options, compilation order, and other compilation-related features.