我有一个使用math.h中的log函数的库。当我编译和打包这个库时,我没有编译错误,这是正常的(我认为)。
现在,当我尝试在应用程序中使用库时,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
为什么会这样?唯一可行的解决方案是,当我编译使用该库的程序时,我必须向gcc提供-lm
选项(即使程序本身不使用math.h),但我发现这很麻烦做。
我在编译库时也尝试提供-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 ...
答案 0 :(得分:4)
在gcc -c
命令中,-lm
并未做任何事情。它是一个链接器选项,而-c
表示不会链接"。
-lm
放置-llist
的正确位置实际上是在pkg-config
之后使用它。这就是静态库依赖关系的完成方式。把它放在liblist的文档中。
如果你想要更高级的东西,那就是pkg-config --static --libs liblist
。使用适当的配置文件,-llist -lm
将输出L = newL
。