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 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答