pretty

Friday 13 November 2015

How to link pre-built library with CMake


1. Provide path to library (for example, default path may be set to usr/local/lib on Linux, and the lib won't be found even when located in the same directory as CMakeLists.txt and even with full path provided inside target_link_libraries). Suppose library is in the subfolder /lib of the folder where CMakeLists.txt resides, then:
set(PATH_TO_LIB ${CMAKE_CURRENT_LIST_DIR}/lib/)
find_library(MyLibVariable NAMES "MyLibrary" PATHS ${PATH_TO_LIB} NO_DEFAULT_PATH)
NAMES should provide the name of library, without the lib prefix. So if there is libMyLibrary.so it shoud read "MyLibrary". NO_DEFAULT_PATH removes all default paths from search. CMAKE_CURRENT_LIST_DIR is the directory where CMakeLists.txt is located.

2. Use target_link_libraries on the found library, presented by MyLibVariable
target_link_libraries(${APP_NAME} 
    ${MyLibVariable}
)
APP_NAME is the name of application to link the library to, added with add_executable(${APP_NAME} ${SRC} ${HEADERS}) in this CMakeLists.txt
In case the library still cannot be located you can debug the path is really the one you suppose it should be, including in CMakeLists.txt the following:
MESSAGE('--- MyLibVariable ---')
MESSAGE(${MyLibVariable})
In case path is still wrong make sure to delete the CMakeCache.txt, as it might have cached previous value.

No comments :

Post a Comment