[C++][CMake][Error] set_target_properties called with incorrect number of arguments

1 简介

这篇文章将探讨了在使用 CMake 构建 C++ 项目时,调用 set_target_properties 函数时参数数量不正确所引发的问题。

2 错误案例

以下为可能发生错误的案例

include_directories (${CMAKE_SOURCE_DIR}/common)
find_package(Threads)

add_library (libusbmuxd SHARED libusbmuxd.c sock_stuff.c ${CMAKE_SOURCE_DIR}/common/utils.c)
find_library (PTHREAD pthread)
target_link_libraries (libusbmuxd ${CMAKE_THREAD_LIBS_INIT})

# 'lib' is a UNIXism, the proper CMake target is usbmuxd
# But we can't use that due to the conflict with the usbmuxd daemon,
# so instead change the library output base name to usbmuxd here
set_target_properties(libusbmuxd PROPERTIES OUTPUT_NAME usbmuxd)
set_target_properties(libusbmuxd PROPERTIES VERSION ${LIBUSBMUXD_VERSION})
set_target_properties(libusbmuxd PROPERTIES SOVERSION ${LIBUSBMUXD_SOVERSION})

install(TARGETS libusbmuxd
    ARCHIVE DESTINATION lib${LIB_SUFFIX}
    LIBRARY DESTINATION lib${LIB_SUFFIX}
)
install(FILES usbmuxd.h usbmuxd-proto.h DESTINATION include)

以上文件可能报错如下:

CMake error at CMakeLists.txt:12 (set_target_properties):
    set_target_properties called with incorrect number of arguments

3 原因分析

set_target_properties 函数的语法格式为

SET_TARGET_PROPERTIES(
    target1 target2 ... targetM
    PROPERTIES 
    prop1 val1 prop2 val2 ... propN valN
)

变量 LIBUSBMUXD_VERSION 和 LIBUSBMUXD_SOVERSION 未定义,因此命令的语法是

SET_TARGET_PROPERTIES(target PROPERTIES name value)

很显然,这里少了 value 变量

4 解决方法

要解决这个问题,请尝试引用变量;使用 $ {LIBUSBMUXD_SOVERSION} 应确保即使变量未定义,它也会采用空字符串的值,从而遵守语法。

include_directories (${CMAKE_SOURCE_DIR}/common)
find_package(Threads)

add_library (libusbmuxd SHARED libusbmuxd.c sock_stuff.c ${CMAKE_SOURCE_DIR}/common/utils.c)
find_library (PTHREAD pthread)
target_link_libraries (libusbmuxd ${CMAKE_THREAD_LIBS_INIT})

# 'lib' is a UNIXism, the proper CMake target is usbmuxd
# But we can't use that due to the conflict with the usbmuxd daemon,
# so instead change the library output base name to usbmuxd here
set_target_properties(libusbmuxd PROPERTIES OUTPUT_NAME usbmuxd)
set_target_properties(libusbmuxd PROPERTIES VERSION " ${LIBUSBMUXD_VERSION}")
set_target_properties(libusbmuxd PROPERTIES SOVERSION " ${LIBUSBMUXD_SOVERSION}")

install(TARGETS libusbmuxd
    ARCHIVE DESTINATION lib${LIB_SUFFIX}
    LIBRARY DESTINATION lib${LIB_SUFFIX}
)
install(FILES usbmuxd.h usbmuxd-proto.h DESTINATION include)
posted @ 2024-11-30 12:17  Zheng-Bicheng  阅读(215)  评论(0)    收藏  举报