用GCC创建自己的静态、共享库

2015-11-08  本文已影响193人  hanashin

创建静态库

1.首先将源文件编译为目标文件

gcc -c calc_mean.c -o calc_mean.o

2.使用ar命令将目标文件打包成静态库

ar  rcs libmean.a      calc_mean.o

关于ar

    ar,Linux系统的一个备份压缩命令,用于创建、修改备存文件(archive),或从备存文件中提取成员文件。ar命令最常见的用法是将【目标文件】打包为【静态链接库】。

例如:ar rcs libutil.a algorithm.o converter.o processor.o 

三个常用的选项参数:

r    把目标文件加入到库中,若已经存在则替换掉原来的目标文件

c    若库不存在,则新建库

s    写入一个目标文件索引到库中,或者更新一个存在的目标文件索引

[注意:静态链接库的名称必须以lib开头,并以.a为后缀]


创建共享库

1.首先也是将源文件编译成目标文件,只是使用-fPIC参数

gcc -c -fPIC calc_mean.c -o calc_mean.o

2.将目标文件链接成共享库

gcc -shared -Wl,-soname,libmean.so.1 -o libmean.so.1.0.1  calc_mean.o

关于gcc的一些参数

-fPIC    Position independant code, needed for shared libraries. (I am a bit in the dark what exactly the difference between -fpic and -fPIC is. It seems that -fPIC works always while -fpic produces smaller object files.)

-Wl,option    Pass option as an option to the linker. If option contains commas, it is split into multiple options at the commas. That is, the commas are replaced with spaces.

-shared          This is actually an option to the linker, not the compiler.

库文件的编译使用

1.静态库的调用

gcc -o test main.c -I头文件的路径 -L库文件的路进 -ltest

如果把头文件和库文件复制到gcc默认的头文件目录/usr/include和/usr/lib里面,那么编译程序就跟标准库函数调用一模一样了

gcc -o test main.c -ltest

2.动态库的调用

$ gcc main.c libtest.so (直接指定与 libmylib.so 连结)

或用

$ gcc main.c -L. -ltest (linker 会在当前目录下搜寻 libtest.so 来进行连结)

如果目录下同时有 static 与 shared library 的话,会以 shared 为主。

使用 -static 参数可以避免使用 shared 连结。

$ gcc main.c -static -L. -ltest

参考链接

Creating a shared and static library with the gnu compiler

linux下制作发布自己的静态库

用GCC制作Library

上一篇 下一篇

猜你喜欢

热点阅读