Executable searching for the linked library in different path than the one set using LD_LIBRARY_PATH

38 Views Asked by At

I am building a C++ application using CMake. This application is supposedly to be run on VxWorks OS. This application needs a shared library which is built externally and imported to the project.

I have linked the library to the application as shown below:

set(MYLIB_PATH"${CMAKE_CURRENT_SOURCE_DIR}/../../my/lib/}")
add_library(MYLIB SHARED IMPORTED)
set_property(TARGET MYLIB PROPERTY IMPORTED_LOCATION ${MYLIB_PATH}/libmylib.so)

target_link_libraries(MyApplication PUBLIC MYLIB)

I am able to build the application successfully. Now, I am placing the binaries on the AARCH64 target. Below is my target directory structure:

work
    ├── bin
    └── lib

I have placed the application in bin and the library in lib. When I try to execute the application, I get error that says:

--> cannot open "/home/k271k9/workspace/software/apps/../../my/lib/libmylib.so"

I did export the environment LD_LIBRARY_PATH=$LD_LIBRARY_PATH:../lib , I verified this by using ldd command and also other libraries that I am linking are correctly linked from the lib directory.

Is there something wrong in what I am doing?

How can I make the application to find the the library in the lib path. & can someone explain why is the executable looking for the library in the local path where I built the application?

1

There are 1 best solutions below

0
Employed Russian On

Is there something wrong in what I am doing?

Yes. There are two problems:

  • Your actual link command has this argument /home/k271k9/workspace/software/apps/../../my/lib/libmylib.so, and
  • the library does not have SONAME in it.

Given these two conditions, the linker hard-codes the absolute path to the library into your executable as a NEEDED entry, and your executable will look for that library at the above path (and only at the above path).

Step 1: verify the statements above:

  • look at the actual link command
  • run readelf -d /home/k271k9/workspace/software/apps/../../my/lib/libmylib.so | grep SONAME (should produce no output).
  • run readelf -d your_binary | grep NEEDED (should show the absolute path: /home/k271k9/.../libmylib.so).

Step 2: fix the problems.

If you are building the libmylib.so yourself, adding -Wl,-soname,libmylib.so will add SONAME tag to it, and then everything else will just work™.

Also, linking with /path/to/libmylib.so is ill-advised. It is nearly always better to link with -L/path/to -lmylib instead. Doing this will also solve your problem (without adding SONAME).