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
- -O0, no optimization
- -O1, -O, late cycle test, default value
- -O2, production use
- -O3, generate optimized executable file
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");
}
- gcc -c -fpic -I include src/util.c, generate util.o
- gcc -shared -o lib/libhello.so util.o, generate dynamic library
- gcc -o hello.e -I include src/main.c -L ./lib -lhello, compile main.c and link library
- 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
- ./hello.e, run the program
Search Path
include
- -I, specify search path for header files
- C_INCLUDE_PATH
- /usr/local/include, default directory of .h files
library
- -L, specify search path for libries
- LD_LIBRARY_PATH
- /lib, /usr/lib, default directory of .so, .lib, and .dll files
Reference