Generate static and dynamic link libraries with gcc

发布于 2019-10-12  15 次阅读


0x1 Comple multiple source files at once

Now we have three source files below:

add.h

#ifndef ADD_H 
#define ADD_H 
    int add(int a, int b); 
#endif

add.c

int add(int a, int b){
    return a + b;
}

main.c

#include "add.h"
int main(){
	int a = 1, b = 2;
	printf("a + b = %d\n", add(a, b));
	return 0;	
}

We compile these files into an excutable file called "main"

demo$ ls
add.c  add.h  main.c
demo$ gcc -c add.c -o add.o # use -c to obtain an object file which is not linked yet
demo$ gcc -c main.c -o main.o 
demo$ gcc add.o main.o -o main 
demo$ ls
add.c  add.h  add.o  main  main.c  main.o
demo$ ./main 
a + b = 3

But for convenience, we generally use this rather than doing the above process:

demo$ gcc main.c add.c -o main
demo$ ./main 
a + b = 3

0x2 Get "main" work using static link library

Let's present the whole process first:

demo$ ls
add.c  add.h  main.c
demo$ gcc -c add.c -o add.o
demo$ ar rcs libadd.a add.o
demo$ ls
add.c  add.h  add.o  libadd.a  main.c
demo$ gcc main.c -L ./ -l add -o main
demo$ ./main
a + b = 3

And here is corresponding explanation:

  • Use "ar" command to generate a static link library, whose name begin with "lib" and end with ".a" (this is naming convertion). And there are three parameters followed:
    • r Insert the files member
    • c Create the archive
    • s Add an index to the archive
  • Use gcc's parameter "-L" to specify the path to the link library file as "./"
  • Use gcc's parameter "- l " to specify the name of our link library file as "add". (yes, the name should be "add" instead of "libadd.a", "lib" and ".a" is always not needed.)

0x3 Get "main" work using dynamic link library

As the same, present the whole process first:

demo$ ls
add.c  add.h  libadd.a  main.c
demo$ rm libadd.a 
demo$ ls
add.c  add.h  main.c
demo$ gcc -shared add.c -o libadd.so
demo$ gcc main.c -L ./ -l add -o main # as the same
demo$ ls
add.c  add.h  libadd.so  main  main.c
demo$ ./main 
./main: error while loading shared libraries: libadd.so: cannot open shared object file: No such file or directory

And here is corresponding explanation:

  • Use gcc's parameter "-shared" to generate a dynamic link library.

The error message says that the linker can't find the shared library. This is because our "libadd.so" is not in ld's search path. So we export our path to the environmental variable " LD_LIBRARY_PATH":

demo$ export LD_LIBRARY_PATH=$(pwd)
demo$ ./main 
a + b = 3

Then our system done it well.