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

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

问题描述

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



我总是被教导说,所有静态或非静态的库都可以与-l ...链接,但是到目前为止我已经遇到了一个库(GLFW),它可以如果我尝试以这种方式链接它,那么什么都不是,但是会喷出未定义的引用链接错误。

根据这个问题,链接静态库的正确方式是直接包含它们以及我自己的对象文件,而不是使用-l。而且,就GLFW图书馆而言,这当然可以解决这个问题。但是我使用的其他静态库在与-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?

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.

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.

So:

  • What could cause this one library to not work when linked rather than included directly? If I knew the cause, maybe I could edit and recompile the library to fix the issue.
  • Is it true that you're not supposed to link static libraries the same way you link shared libraries? (And if not, why not?)
  • Is the linker still able to eliminate unused library functions from the output executable when the library is directly included in this way?

解决方案

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天全站免登陆