使用 GCC 链接静态库的正确方法 [英] Proper way to link a static library using GCC

查看:94
本文介绍了使用 GCC 链接静态库的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么有些静态库 (lib*.a) 可以像链接共享库 (lib*.so) 一样链接(ld -l 开关),而有些则不能?

Why is it that some static libraries (lib*.a) can be linked in the same way that shared libraries (lib*.so) are linked (ld -l switch), but some can not?

我一直被教导所有的库,不管是不是静态的,都可以用 -l... 链接,但是到目前为止我遇到了一个库(GLFW),它除了喷出未定义的引用"链接之外什么也没做如果我尝试以这种方式链接它,则会出错.

I had always been taught that all libraries, static or not, can be linked with -l..., however I've run into one library so far (GLFW), which does nothing but spew "undefined reference" link errors if I attempt to link it this way.

根据this question上的回复,正确"的方式链接静态库是直接包含它们,以及我自己的目标文件,而不是使用 -l.而且,在 GLFW 库的情况下,这当然可以解决问题.但是我使用的所有其他静态库在与 -l 链接时都可以正常工作.

According to the response on this question, the "proper" way to link static libraries is to include them directly, along with my own object files, rather than using -l. And, in the case of the GLFW library, this certainly solves the issue. But every other static library I'm using works just fine when linked with -l.

所以:

  • 是什么原因导致这个库在链接而不是直接包含时无法工作?如果我知道原因,也许我可以编辑并重新编译库来解决问题.
  • 您不应该像链接共享库一样链接静态库吗?(如果没有,为什么不呢?)
  • 当以这种方式直接包含库时,链接器是否仍然能够从输出可执行文件中消除未使用的库函数?

推荐答案

感谢您的回复!原来问题是由于链接顺序.显然,如果您使用的库又具有其他库依赖项,则必须将这些其他依赖项列在 库之后,而不是像我之前所做的那样.学到了新东西!

Thanks for the replies! Turns out the problem was due to link order. Apparently, if you use a library which in turn has other library dependencies, those other dependencies must be listed after the library, not before as I had been doing. Learned something new!

这篇关于使用 GCC 链接静态库的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆