2016-10-03 79 views
0

我有一个使用math.h中的日志函数的库。当我编译和打包这个库时,我没有收到编译错误,这是正常的(我认为)。将静态库与C数学库正确链接

现在,当我尝试使用库的应用程序,GCC给我链接错误:

Compiling mytestlist using "mytestlist.o": 
gcc mytestlist.o -I/student/cmpt332/pthreads -I. -std=c99 -Wall -pedantic -L. -L/student/cmpt332/pthreads/lib/linuxx86_64/ -llist -o mytestlist 
./liblist.a(list_adders.o): In function `NodeCreate': 
list_adders.c:(.text+0x343): undefined reference to `log' 
./liblist.a(list_adders.o): In function `ListCreate': 
list_adders.c:(.text+0x62f): undefined reference to `log' 
./liblist.a(list_adders.o): In function `ListFree': 
list_adders.c:(.text+0xdcc): undefined reference to `log' 
list_adders.c:(.text+0xe55): undefined reference to `log' 
list_adders.c:(.text+0xefb): undefined reference to `log' 
./liblist.a(list_adders.o):list_adders.c:(.text+0xf96): more undefined references to `log' follow 
collect2: error: ld returned 1 exit status 
Makefile:47: recipe for target 'mytestlist' failed 
make: *** [mytestlist] Error 1 

这究竟是为什么?唯一可行的解​​决方案是我编译使用该库的程序时(即使程序本身不使用math.h),我必须向gcc提供-lm选项,但我觉得这样做很麻烦。

我也尝试在编译库时提供-lm选项,但是当使用库编译应用程序时,我会得到相同的链接器错误。

有没有办法用math.h编译库,而不必为使用该库的其他程序提供-lm

在你想知道的话,我编译,构成了使用该库的每个对象:

gcc -std=c99 -Wall -pedantic -static -I. -c list_adders.c -o list_something.o -lm 

中,库使用包装:

ar cvfr liblist.a list_something.o ... 
+3

静态库未链接。没有办法将它与数学库链接,因为根本没有办法链接它。您链接应用程序或共享库,但不是静态库。也没有办法在库中标记或记录静态库的依赖关系。 –

回答

4

在你gcc -c命令时, -lm没有做任何事情。这是一个链接器选项,并且-c表示“不链接”。

-lm的适当位置实际上是在您使用它后的-llist之后。这就是静态库依赖关系的完成方式。把它放在liblist的文档中。

如果您想要更有趣的作品,请点击这里pkg-config。使用适当的配置文件,pkg-config --static --libs liblist将输出-llist -lm