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

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?

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

Add CURRENT_PATH/lib to /etc/ld.so.conf or /etc/ld.so.conf.d/mylib.conf and run sudo ldconfig

Also use the full path for -I and -L in CFLAGS & LDFLAGS, respectively.