• 链接静态库


    在应用程序需要连接外部库的情况下,linux默认对库的连接是使用动态库,在找不到动态库的情况下再选择静态库。使用方式为:
    gcc test.cpp -L. -ltestlib
    如果当前目录有两个库libtestlib.so libtestlib.a 则肯定是连接libtestlib.so。如果要指定为连接静态库则使用:
    gcc test.cpp -L. -static -ltestlib
    使用静态库进行连接。

    当对动态库与静态库混合连接的时候,使用-static会导致所有的库都使用静态连接的方式。这时需要作用-Wl的方式:
    gcc test.cpp -L. -Wl,-Bstatic -ltestlib  -Wl,-Bdynamic -ltestdll 
    另外还要注意系统的运行库使用动态连接的方式,所以当动态库在静态库前面连接时,必须在命令行最后使用动态连接的命令才能正常连接
    ,如:
    gcc test.cpp -L. -Wl,-Bdynamic -ltestdll -Wl,-Bstatic -ltestlib  -Wl,-Bdynamic
    最后的-Wl,-Bdynamic表示将缺省库链接模式恢复成动态链接。

    其中用到的两个选项:-Wl,-Bstatic和-Wl,-Bdynamic。这两个选项是gcc的特殊选项,它会将选项的参数传递给链接器,作为链接器的选项。比如-Wl,-Bstatic告诉链接器使用-Bstatic选项,该选项是告诉链接器,对接下来的-l选项使用静态链接;-Wl,-Bdynamic就是告诉链接器对接下来的-l选项使用动态链接。下面是man gcc对-Wl,option的描述,
    -Wl,option Pass option as an option to the linker. If option contains commas, it is split into multiple options at the commas. You can use this syntax to pass an argument to the option. For example, -Wl,-Map,output.map passes -Map output.map to the linker. When using the GNU linker, you can also get the same effect with -Wl,-Map=output.map.
    下面是man ld分别对-Bstatic和-Bdynamic的描述,
    -Bdynamic -dy -call_shared Link against dynamic libraries. You may use this option multiple times on the command line: it affects library searching for -l options which follow it. -Bstatic -dn -non_shared -static Do not link against shared libraries. You may use this option multiple times on the command line: it affects library searching for -l options which follow it. This option also implies --unresolved-symbols=report-all. This option can be used with -shared. Doing so means that a shared library is being created but that all of the library's external references must be resolved by pulling in entries from static libraries

    linux 链接库文件出现“undefined reference to" 问题的解决方法
    http://blog.csdn.net/u013897132/article/details/48156941

    因此,我们需要注意,在链接命令中给出所依赖的库时,需要注意库之间的依赖顺序,依赖其他库的库一定要放到被依赖库的前面,这样才能真正避免undefined reference的错误,完成编译链接。

  • 相关阅读:
    让他人变得优秀是伟大
    年龄越大,离家越远
    秋天的叶子
    [短彩信]C#短彩信模块开发设计(2)——配置
    jquery实现网页二级菜单简单代码
    HTML页面做中间页跳转传递参数
    ToJson
    Button页面中的按钮
    SQLSERVER 18056 错误
    在桌面添加可拖动/点击的悬浮窗口
  • 原文地址:https://www.cnblogs.com/xingmuxin/p/11416518.html
Copyright © 2020-2023  润新知