https://blog.csdn.net/tttyd/article/details/8722276

 

方法一:在配置文件/etc/ld.so.conf中指定动态库搜索路径。 
vi /etc/ld.so.conf 
添加 lib目录 
ldconfig 
方法二:通过环境变量LD_LIBRARY_PATH指定动态库搜索路径。 
export LD_LIBRARY_PATH=”LD_LIBRARY_PATH:/opt/” 
方法三:在编译目标代码时指定该程序的动态库搜索路径。 
还可以在编译目标代码时指定程序的动态库搜索路径。通过gcc 的参数”-Wl,-rpath,”指定

 

其中方法三可以避免安装部署的麻烦

方法三示例

 

 

假设main.cpp,hello.h,hello.cpp,其中main.cpp调用了hello类中的方法

1 生成hello.so

  g++ -shared hello.cpp -o libhello.so

2 编译main.cpp,并链接,并指定运行时libhello.so的位置

  g++ main.cpp -lhello -L./ -Wl,-rpath=./ -o main

 

值得一提的是,如果采用带版本号的库,例如libhello.so.2

链接命令可使用g++ main.cpp libhello.so.2 -L./ -Wl,-rpath=./ -o main

 

2)加入第二个so库

g++ main.cpp -L./second/ -Wl,-rpath=./second/ -lsecond -L./hello/ -Wl,-rpath=./hello/ -lhello  -o main

 

ps,遇到过一个奇怪的问题,就是假设libhello.so还用到了libother.so,由于在/etc/ld.so.conf里配置错误了libother.so的目录路径,导致一直产生undefined reference to错误,但是在工程里对libother目录路径配置是正确的,有可能于查找路径顺序有关

假设main.cpp,hello.h,hello.cpp,其中main.cpp调用了hello类中的方法

1 生成hello.so

  g++ -shared hello.cpp -o libhello.so

2 编译main.cpp,并链接,并指定运行时libhello.so的位置

  g++ main.cpp -lhello -L./ -Wl,-rpath=./ -o main

 

值得一提的是,如果采用带版本号的库,例如libhello.so.2

链接命令可使用g++ main.cpp libhello.so.2 -L./ -Wl,-rpath=./ -o main

 

2)加入第二个so库

g++ main.cpp -L./second/ -Wl,-rpath=./second/ -lsecond -L./hello/ -Wl,-rpath=./hello/ -lhello  -o main

 

ps,遇到过一个奇怪的问题,就是假设libhello.so还用到了libother.so,由于在/etc/ld.so.conf里配置错误了libother.so的目录路径,导致一直产生undefined reference to错误,但是在工程里对libother目录路径配置是正确的,有可能于查找路径顺序有关

相关文章:

  • 2021-06-11
  • 2021-06-06
  • 2022-12-23
  • 2022-12-23
  • 2021-07-01
  • 2022-12-23
  • 2022-12-23
  • 2021-09-26
猜你喜欢
  • 2021-12-03
  • 2021-08-11
  • 2022-02-27
  • 2021-12-23
  • 2022-01-08
相关资源
相似解决方案