Common workflow with libraries searched by pkg-config within CMake:
# Use pkg-config for search library `xxx`.
pkg_check_modules(XXX xxx)
# Build target which uses given library
# The only command which has no target-oriented equivalent.
# But see comments after the code.
link_directories(${XXX_LIBRARY_DIRS})
# Two global commands belows can be replaced by target-oriented equivalent
# after creation of the target.
include_directories(${XXX_INCLUDE_DIRS})
add_compile_options(${XXX_CFLAGS_OTHER})
# Create target
add_executable(my_exe ...) # Or add_library()
# The only target-oriented command, which has no global equivalent.
target_link_libraries(my_exe ${XXX_LDFLAGS_OTHER}) # It is OK to have link flags here
target_link_libraries(my_exe ${XXX_LIBRARIES}) # Can be combined with previous call.
Note, that we use XXX_LDFLAGS_OTHER
variable instead of XXX_LDFLAGS
one. This is because XXX_LDFLAGS
includes -l
and -L
options for which CMake has more suitable commands. Similar reason about usage of XXX_CFLAGS_OTHER
.
Currently, CMake doesn't recommend to use link_directories command but use absolute paths to libraries in target_link_libraries call. One can extract absolute paths to libraries, listed by pkg-config, with use of find_library command:
...
# Instead of using `link_directories`, collect absolute paths to libraries.
set(XXX_LIBS_ABSOLUTE)
foreach(lib ${XXX_LIBRARIES})
# Choose name of variable, which will contain result of `find_library`
# for specific library.
set(var_name XXX_${lib}_ABS)
# Search library under dirs, returned by pkg-config.
find_library(${var_name} ${lib} ${XXX_LIBRARY_DIR})
list(APPEND XXX_LIBS_ABSOLUTE ${${var_name}})
endforeach()
# Instead of `target_link_libraries(my_exe ${XXX_LIBRARIES})`
target_link_libraries(my_exe ${XXX_LIBS_ABSOLUTE})