Example of a C Program Comprised of Two Source Files

The following example shows a C program source comprised of two source files. The main and max functions are in separate files. The program logic starts with the main function.

Example Program with Two Source Files
/***********************************************************
*  Source file 1 - main function                           *
************************************************************/
 
#define ONE     1
#define TWO     2
#define THREE   3
 
extern int max(int, int);          /* Function declaration */
 
int main(int argc, char * argv[])  /* Function definition  */
{
   int u, w, x, y, z;
 
   u = 5;
   z = 2;
   w = max(u, ONE);
   x = max(w,TWO);
   y = max(x,THREE);
   z = max(y,z);
return z;
}
/***********************************************************
*  Source file 2 - max function                            *
************************************************************/
int max (int a,int b)             /* Function  definition  */
{
   if ( a > b )
       return (a);
   else
       return (b);
}

The first source file declares the function max, but does not define it. This is an external declaration, a declaration of a function defined in source file 2. Four statements in main are function calls of max.

The lines beginning with a number sign (#) are preprocessor directives that direct the preprocessor to replace the identifiers ONE, TWO, and THREE with the digits 1, 2, and 3. The directives in the first source file do not apply to the second source file.

The second source file contains the function definition for max, which is called four times in main. After you compile the source files, you can link and run them as a single program.



Internal Structure of a C or C++ Program
Scope of Identifier Visibility
Statement Blocks


Example of a Simple C Program