繁体   English   中英

将静态库与 C 数学库正确链接

[英]Properly Linking a static library with the C math library

我有一个使用 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 ...

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

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

如果你想要更高级的东西,有pkg-config 使用适当的配置文件, pkg-config --static --libs liblist将输出-llist -lm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM