gcc
Options
  • gcc -o hello.e hello.c, compile hello.c, output the executable file hello.e
  • gcc -g hello.c, compile hello.c and generate debug information for gdb
  • gcc -O hello.c, compile hello.c and generate optimized executable program
  • gcc -v hello.c, output the detailed information of compiling
  • gcc -Wall hello.c, generate more warning details
  • Simple File
    #include <stdio.h>
    
    int main()
    {
    	printf("Hello World!\n");
    
    	return 0;
    }
    		

    Multiple Files
    // main.c
    extern void disp();
    
    int main()
    {
    	disp();
    
    	return 0;
    }
    		
    // util.c
    #include <stdio.h>
    
    void disp()
    {
    	printf("Hello World!\n");
    }
    		
  • gcc -c main.c, generate main.o
  • gcc -c util.c, generate util.o
  • gcc main.o util.o -o hello.e, generate hello.e
  • Link Libraries

    // util.h
    #ifndef UTIL_H
    #define UTIL_H
    
    void disp();
    
    #endif
    		
    // main.c
    #include "util.h"
    
    int main()
    {
    	disp();
    
    	return 0;
    }
    		
    // utill.c
    #include <stdio.h>
    #include "util.h"
    
    void disp()
    {
    	printf("Hello World!\n");
    }
    		
    1. gcc -c -fpic -I include src/util.c, generate util.o
    2. gcc -shared -o lib/libhello.so util.o, generate dynamic library
    3. gcc -o hello.e -I include src/main.c -L ./lib -lhello, compile main.c and link library
    4. Making library available at run time
      • export LD_LIBRARY_PATH=$PWD/lib:$LD_LIBRARY_PATH, add "lib" folder to search directory
      • gcc -L ./lib -Wl,-rpath=$PWD/lib -Wall -o test -I include src/main.c -lhello, using rpath which is run time search path
      • cp lib/libhello.so /usr/lib, chmod 0755 /usr/lib/libhello.so, ldconfig
    5. ./hello.e, run the program
    Search Path
  • include
  • library
  • Reference
  • rpath
  • Options for Directory Search
  • Shared libraries with GCC on Linux
  • gcc commands