3

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Francesco Cina
  • 907
  • 1
  • 11
  • 19

1 Answers1

5

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
Francesco Cina
  • 907
  • 1
  • 11
  • 19
  • That did the trick for me - it's worth pointing out that, because the linker is invoked via the gcc front end, you need to use the `-Wl,-rpath=` version rather than `ld`'s own `-R` or `-rpath` option - it won't work without `-Wl,` on the beginning as CGO will reject it. – M_M Jun 12 '20 at 07:52