The C compiler cammands (options) used to compile a multiple files C program

  • Suppose a C program consists of N program files

      prog1.c   prog2.c   prog3.c   ...   progN.c 

  • The following C compiler commands are used to compile this multi files C program:

      gcc  -c  prog1.c       // Compile program file prog1.c
                             // Generates the object file prog1.o
      gcc  -c  prog2.c       // Compile program file prog2.c
                             // Generates the object file prog2.o
      ...
      gcc  -c  progN.c       // Compile program file progN.c
                             // Generates the object file progN.o
    
      gcc  -o  myProg  prog1.o  prog2.o  prog3.o  ... progN.o  
                             // Links the object files into 
    			 // the executable program myProg
    

Example compiling C program consisting of 2 program files

Example:   the following C program that consists of 2 program files:

main1.c func1.c
#include <stdio.h>

// Notice: no function declaration used

int main(int argc, char *argv[])
{
    int a = 4, b;

    b = square(a);
    printf("square(%d) = %d\n", a, b);
}
int square( int x )        
{
    int r;              

    r = x * x;      
    return ( r );  
}



  

Commands used to compile this C program:

  gcc  -c  main1.c                 # Compile main1.c
  gcc  -c  func1.c		   # Compile func1.c

  gcc -o main1   main1.o  func1.o  # Link 


Not preferred: (can be use with smaller number of program files) gcc -o main1 main1.c func1.c

DEMO: demo/C/set4/main1.c + func1.c

How to re-compile a multiple file C program after changing some source files

  • Compilation rule:

    • A C program file progk.c that has been changed/modified must be re-compile with:

        gcc  -c   progk.c   # Compile the updated file
      

    • C program files that has not been changed/modified, do not need to be compiled again.


  • Linking rule:

    • When you re-compile any C program file, you must re-link the object files again using:

         gcc -o progName  prog1.o prog2.o  ... progN.o

Example re-compiling a C program

Suppose we made a change in the program file main1.c:

main1.c func1.c
#include <stdio.h>

int main(int argc, char *argv[])
{
    int a = 4, b;

    b = square(a);
    printf("%d^2 = %d\n", a, b);
}
int square( int x )        
{
    int r;              

    r = x * x;      
    return ( r );  
}

  

Commands used to re-compile this C program into the executable program are:

  gcc  -c  main1.c                 # Re-compile main1.c

  gcc -o main1   main1.o  func1.o  # Link 

DEMO: demo/C/set4/main1.c + func1.c