简体   繁体   English

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

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

I have a library which uses the log function from math.h.我有一个使用 math.h 中的 log 函数的库。 When I compile and package this library, I get no compilation errors, which is normal (I think).当我编译和打包这个库时,我没有得到编译错误,这是正常的(我认为)。

Now when I try to use the library in an application, gcc gives me linker errors:现在,当我尝试在应用程序中使用该库时,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

Why is this happening?为什么会这样? The only solution that works is that I have to supply the -lm option to gcc when I compile the program that uses the library (even though the program itself makes no use of math.h), however I find this cumbersome to do.唯一有效的解决方案是,当我编译使用库的程序时,我必须向 gcc 提供-lm选项(即使程序本身不使用 math.h),但是我发现这样做很麻烦。

I've also tried supplying the -lm option when compiling the library, but when the application is compiled using the library, I get the same linker errors.我还尝试在编译库时提供-lm选项,但是当使用该库编译应用程序时,我遇到了相同的链接器错误。

Is there a way to compile the library with math.h without having to supply -lm to other programs that make use of the library?有没有办法用 math.h 编译库,而不必将-lm给使用该库的其他程序?

In case you're wondering, I compile each object that makes up the library using:如果您想知道,我使用以下方法编译构成库的每个对象:

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

And the library is packaged using:该库使用以下方法打包:

ar cvfr liblist.a list_something.o ...

In your gcc -c command, the -lm isn't doing anything.在您的gcc -c命令中, -lm没有做任何事情。 It's a linker option, and -c means "don't link".这是一个链接器选项, -c表示“不链接”。

The proper place to put -lm is in fact after the -llist whenever you use it.放置-lm的正确位置实际上是在您使用它时的-llist之后。 That's how static library dependencies are done.这就是静态库依赖项的完成方式。 Put it in the documentation for liblist.把它放在 liblist 的文档中。

If you want something fancier, there's pkg-config .如果你想要更高级的东西,有pkg-config With the appropriate configuration files, pkg-config --static --libs liblist will output -llist -lm .使用适当的配置文件, pkg-config --static --libs liblist将输出-llist -lm

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

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