解决C++编译时报错:ld: cannot find -lxxx方法

编译程序有时会遇到“ld: cannot find -lxxx”的错误,就是链接器说找不到xxx库。一般先使用如下命令查找系统中是否存在xxx库而ld程序未找到(以zlib为例):

$ ld -lzlib --verbose

输出如下信息:

====================================
attempt to open /usr/x86_64-linux-gnu/lib64/libzlib.so failed
attempt to open /usr/x86_64-linux-gnu/lib64/libzlib.a faile
dattempt to open /usr/local/lib64/libzlib.so failed
attempt to open /usr/local/lib64/libzlib.a failed
attempt to open /lib64/libzlib.so failed
attempt to open /lib64/libzlib.a failed
attempt to open /usr/lib64/libzlib.so failed
attempt to open /usr/lib64/libzlib.a failed
attempt to open /usr/x86_64-linux-gnu/lib/libzlib.so failed
attempt to open /usr/x86_64-linux-gnu/lib/libzlib.a failed
attempt to open /usr/local/lib/libzlib.so failed
attempt to open /usr/local/lib/libzlib.a failed
attempt to open /lib/libzlib.so failed
attempt to open /lib/libzlib.a failed
attempt to open /usr/lib/libzlib.so failed
attempt to open /usr/lib/libzlib.a failed
/usr/bin/ld.bfd.real: cannot find -lzlib
=====================================

此时说明系统中确实未安装zlib库,则下载安装zlib库,并将安全路径加到LD_LIBRARY_PATH即可。

另一种情况,系统中存在库而ld程序未找到,如:

$ ld -lglog --verbose

输出如下信息:

==================================================
attempt to open //usr/x86_64-redhat-linux/lib64/libglog.so failed
attempt to open //usr/x86_64-redhat-linux/lib64/libglog.a failed
attempt to open //usr/lib64/libglog.so failed
attempt to open //usr/lib64/libglog.a failed
attempt to open //usr/local/lib64/libglog.so failed
attempt to open //usr/local/lib64/libglog.a failed
attempt to open //lib64/libglog.so failed
attempt to open //lib64/libglog.a failed
attempt to open //usr/x86_64-redhat-linux/lib/libglog.so failed
attempt to open //usr/x86_64-redhat-linux/lib/libglog.a failed
attempt to open //usr/local/lib/libglog.so succeeded
-lglog (//usr/local/lib/libglog.so)
libgflags.so.2.2 needed by //usr/local/lib/libglog.so
found libgflags.so.2.2 at //usr/local/lib/libgflags.so.2.2
libpthread.so.0 needed by //usr/local/lib/libglog.so
found libpthread.so.0 at //usr/lib64/libpthread.so.0
libstdc++.so.6 needed by //usr/local/lib/libglog.so
found libstdc++.so.6 at //usr/local/lib64/libstdc++.so.6
libm.so.6 needed by //usr/local/lib/libglog.so
found libm.so.6 at //usr/lib64/libm.so.6
libc.so.6 needed by //usr/local/lib/libglog.so
found libc.so.6 at //usr/lib64/libc.so.6
libgcc_s.so.1 needed by //usr/local/lib/libglog.so
found libgcc_s.so.1 at //usr/lib64/libgcc_s.so.1
ld-linux-x86-64.so.2 needed by //usr/lib64/libpthread.so.0
found ld-linux-x86-64.so.2 at //usr/lib64/ld-linux-x86-64.so.2
ld: warning: cannot find entry symbol _start; not setting start address

此时说明系统中安装了glog库,但是ld程序未找到。

一种方法是将glog库的路径加到LD_LIBRARY_PATH环境变量中,另一种方法是直接加编译器选项进行编译:

gcc -L/usr/lib64 -lglog

你可能感兴趣的:(C++)