编译时混合使用动态库和静态库

本文介绍了解决g++编译过程中出现的链接错误的方法,特别是针对未找到libstdc++、libm和libc静态库的问题。通过采用动态库与静态库混合编译的方式,有效地解决了这一常见问题。

         编译某个测试代码时,出现了下面的错误:

# g++ -std=c++11 -o testlurkcli main.cpp -L. -llurkcli-lasl -static
/usr/bin/ld: cannot find -lstdc++
/usr/bin/ld: cannot find -lm
/usr/bin/ld: cannot find -lc
collect2: error: ld returned 1 exit status

         这个错误,是在最后的链接阶段,没有找到 libstdc++,libm,libc等这几个库。正常而言,这几个库的动态库都是存在的,这里因为使用了”-static”选项,导致链接时没有找到这几个库的静态版本。

         网上查了一下,大部分是推荐把这几个库的静态库版本找到并软连接到/usr/lib64/中。

         不过这里采用一种动态库和静态库混合编译的方法去解决。具体编译过程如下:

# g++ -std=c++11 main.cpp liblurkcli.a libasl.a -lpthread-o testlurkcli

         或者:

# g++ -std=c++11 main.cpp -L.  -llurkcli -lasl -lpthread -o testlurkcli

         或者:

# g++ -v -std=c++11 main.cpp -L. -Wl,-Bstatic -llurkcli-lasl -Wl,-Bdynamic -lpthread  -otestlurkcli

          注意,最后一种方式,使用-Wl,-Bstatic以及-Wl,-Bdynamic,给连接器ld传递链接选项,-Wl,-Bstatic使得后面的-l库使用静态连接的方式,而-Wl,-Bdynamic使得后面的-l库使用动态链接的方式。所以,上面的命令中,-llurkcli –lasl使用的是静态连接,而-lpthread,以及连接器自己默认连接的-lstdc++, -lm, -lgcc_s, -lgcc, -lc, -lgcc_s, -lgcc,都是采用的动态链接。

         下面的话,摘自:

https://ftp.gnu.org/pub/old-gnu/Manuals/ld-2.9.1/html_node/ld_3.html#SEC3

 

-Bdynamic

-dy

-call_shared

Link against dynamic libraries. This isonly meaningful on platforms for which shared libraries are supported. Thisoption is normally the default on such platforms. The different variants ofthis option are for compatibility with various systems. You may use this optionmultiple times on the command line: it affects library searching for -l optionswhich follow it.

 

-Bstatic

-dn

-non_shared

-static

Do not link against shared libraries. Thisis only meaningful on platforms for which shared libraries are supported. Thedifferent variants of this option are for compatibility with various systems.You may use this option multiple times on the command line: it affects librarysearching for -l options which follow it.

 

转载于:https://www.cnblogs.com/gqtcgq/p/7247024.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值