日期:2014-05-16  浏览次数:20777 次

请教:多个文件如何生成动态链接库(.so)?
以前只是在程序中用一些现成的库,现在要把自己的多个文件封装成一个动态链接库,在网上找个找资料,基本都是说用如下命令:
gcc   -fPIC   -shared   -o   libNAME.so   file1.c   file2.c
这些例子想对比较简单;

我现在要解决的问题是,我的程序对外只提供一个函数接口,但是呢,这个函数却需要调用很多我自己写的文件里面的函数。就是我程序中有很多源文件和头文件,我的Makefile是这样的:

test   :   subNodeList.o   NodeList.o   ParseXml.o   bm.o   distance.o       MatchKey.o   TraitList.o   Tree.o   UpdateRule.o   detect.o   test.o
        gcc   -o       test     subNodeList.o   NodeList.o   ParseXml.o   bm.o   distance.o       MatchKey.o   TraitList.o   Tree.o     UpdateRule.o   detect.o   test.o   -lm     -lxml2
test.o   :   test.c
        gcc   -I   /usr/include/libxml2   -c   -g     test.c
detect.o   :   detect.c   detect.h
        gcc   -I   /usr/include/libxml2   -c   -g   detect.c
UpdateRule.o   :   UpdateRule.c   UpdateRule.h
        gcc   -I   /usr/include/libxml2   -c   -g   UpdateRule.c
Tree.o:   Tree.c   Tree.h
        gcc   -c   -g   Tree.c
TraitList.o:   TraitList.c   TraitList.h
        gcc   -c   -g   TraitList.c
distance.o   :   distance.c   distance.h
        gcc   -c   -g   distance.c
MatchKey.o   :   MatchKey.c   MatchKey.h
        gcc   -c   -g     MatchKey.c
bm.o   :   bm.c   bm.h
        gcc   -c   -g     bm.c  
ParseXml.o:   ParseXml.c   ParseXml.h
        gcc   -I   /usr/include/libxml2   -c   -g     ParseXml.c  
NodeList.o   :   NodeList.c   NodeList.h
        gcc   -c   -g     NodeList.c  
subNodeList.o   :   subNodeList.c   subNodeList.h
        gcc   -c   -g     subNodeList.c  
clean   :  
        rm   -rf   *.o   test

其中,detect.c中包括对外使用的函数接口,test.c里面就是一个main函数,调用这个函数接口,测试用的。

比如subNodeList.c,NodeList.c   Tree.c   等都是我函数中用到的数据结构,而且其中还用到了其他的库。

我感觉文件依赖关系多,而且还调用了其他的库,不知该如何生成库,希望大家指点一下。谢谢!



------解决方案--------------------
在gcc -o里加上 -shared -Wl,-soname,libtest.so就可以了,其他不用改

gcc -shared -Wl,-soname,libtest.so -o libtest.so subNodeList.o NodeList.o ParseXml.o bm.o distance.o MatchKey.o TraitList.o Tree.o UpdateRule.o detect.o test.o -lm -lxml2