带有set_target_properties的FindPkgConfig无法用于设置CFLAGS / LDFLAGS

时间:2016-02-17 13:03:47

标签: build cmake pkg-config

来自FindPkgConfig的

pkg_check_modules会将MYLIBRARY_LDFLAGSMYLIBRARY_CFLAGS作为普通的CMake列表(使用分号分隔符)。

set_target_propertiesset_property只接受一个字符串。

因此它不起作用,因为它不会扩展列表:

set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY LINK_FLAGS ${MYLIBRARY_LDFLAGS})

这与内部的分号相同:

set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY LINK_FLAGS "${MYLIBRARY_LDFLAGS}")

set_target_properties在未引用时扩展为多个字符串,并在引用时扩展为带分号的一个字符串。

我该如何使用它?

2 个答案:

答案 0 :(得分:2)

在CMake中通过pkg-config搜索的库的常用工作流程:

# 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.

注意,我们使用XXX_LDFLAGS_OTHER变量而不是XXX_LDFLAGS变量。这是因为XXX_LDFLAGS 包含 -l-L选项,其中CMake具有更合适的命令。使用XXX_CFLAGS_OTHER的相似原因。

目前,CMake不建议使用link_directories命令,但在target_link_libraries调用中使用库的绝对路径。可以使用find_library命令提取由pkg-config列出的库的绝对路径:

...
# 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})

答案 1 :(得分:0)

我不确定这是否打算如何使用,但这应该有效:

string(REPLACE ";" " " MYLIBRARY_LDFLAGS "${MYLIBRARY_LDFLAGS}")
set_property(TARGET ${PROJECT_NAME} APPEND_STRING PROPERTY LINK_FLAGS " ${MYLIBRARY_LDFLAGS}")

string(REPLACE)命令将更改以空格分隔的字符串中的列表,因此您可以将其用于LINK_FLAGS属性

" ${MYLIBRARY_LDFLAGS}"APPEND_STRING而不是APPEND中的前置空格将确保结果字符串可用作LINK_FLAGS,即使该属性不为空。 / p>