Search code examples
staticcmakelibrariesshared

Cmake: linking shared library


I've done this before a couple of times, but somehow I'm stuck this time. I have an executable "myapp" and a own shared library "mylib". In my cmakelists I have the following:

ADD_LIBRARY(mylib SHARED ${SOURCES_LIB})
INSTALL(TARGETS mylib DESTINATION .)
ADD_EXECUTABLE(myapp ${SOURCES_APP})
TARGET_LINK_LIBRARIES(myapp ${QT_LIBRARIES} mylib)
INSTALL(TARGETS myapp DESTINATION .)

Everything compiles and links correctly, but when I start myapp, I get the following error:

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

The lib and the executable are present in the install directory. When I make my library static by changing the first line of the above cmakelists to:

ADD_LIBRARY(mylib STATIC ${SOURCES_LIB})

then everything works 100%.

Does anyone know what I'm doing wrong?


Solution

  • During the installation of your library and executable, the runtime paths to find the library are stripped from the executable. Therefore your library has to reside in the runtime library search path. For example under Linux, try to set LD_LIBRARY_PATH to the directory that contains the installed library when starting your executable.