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

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

# 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.

 

你可能感兴趣的:(BUG排查,Linux系统编程)