dongtaogu8510 2017-05-26 22:07
浏览 212
已采纳

如何从相对路径使用动态链接库

I would like to use a dynamic C library from a go application, I can build the application but the library is not found at runtime. Here the structure of my project:

src/ctest/
      |- lib/
      |    |- libmylib.so
      |    |- libmylib.h
      |- main.go

in main.go I import the .h and .so files:

/*
#cgo CFLAGS: -I./lib
#cgo LDFLAGS: -L./lib -lmylib
#include <mylib.h>
*/
import "C"

func main() {
    C.testMyLib()
}

I can build the application successfully, but when launched it throws this error:

error while loading shared libraries: libmylib.so.0: cannot open shared object file: No such file or directory

If I copy the libmylib.so file in /usr/lib then everything works as expected; however, I would like that my application automatically searches for the needed library in CURRENT_PATH/lib at runtime without setting environment variables. How can I achieve it?

  • 写回答

2条回答 默认 最新

  • donglu3243 2017-05-27 08:05
    关注

    I was able to solve the issue adding the -Wl,-rpath=\$ORIGIN/lib linker flag to LDFLAGS options in the main.go file:

    package main
    /*
    #cgo CFLAGS: -I${SRCDIR}/lib
    #cgo LDFLAGS: -L${SRCDIR}/lib -Wl,-rpath=\$ORIGIN/lib -luiohook
    #include <uiohook.h>
    */
    import "C"
    
    func main() {
        C.hook_run()
    }
    

    Now when the application is executed, it uses also the CURRENT_FOLDER/lib to search for dynamic libraries (CURRENT_FOLDER is the directory where the application executable is executed).

    For linux users only: If the error is still thrown, you need to create a symlink or to rename the XXX.so library to XXX.so.0. In my case it was:

    src/ctest/
      |- lib/
      |    |- libmylib.so
      |    |- libmylib.so.0 <- symlink to ./libmylib.so
      |    |- libmylib.h
      |- main.go
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘