Cmake add_library别名

时间:2018-11-18 23:27:15

标签: cmake

我正试图弄清楚此github json项目的cmake文件中的this行是什么,

add_library(${NLOHMANN_JSON_TARGET_NAME} INTERFACE)
add_library(${PROJECT_NAME}::${NLOHMANN_JSON_TARGET_NAME} ALIAS ${NLOHMANN_JSON_TARGET_NAME})

特别是在此示例中,这在该cmake文件中允许什么?

在此CMakeLists.cmake中,我看不到对${PROJECT_NAME}::${NLOHMANN_JSON_TARGET_NAME}的其他引用,因此我对实现的目的感到困惑。

编辑:

此操作实现的关键是,注释对我而言并不明显,即当通过add_subdirectory()使用项目时,它使目标与命名空间一起使用

4 个答案:

答案 0 :(得分:1)

使用git的blame函数显示在此提交中添加了以下行:33a2154,其中附加了以下注释:

  

CMake约定是对导入使用项目名称空间,即Foo ::   目标。从项目中导入多个目标时,这看起来   例如Foo :: Bar1 Foo :: Bar2等。这会将nlohmann_json ::名称空间添加到   导出的目标名称。

     

这还允许通过以下方式使用生成的项目配置文件:   构建目录,而不仅仅是安装目录。

答案 1 :(得分:1)

这将允许通过将nlohmann/json项目添加到具有add_subdirectory(...)的超级项目中来使用

例如简单的项目结构:

<root project>\
     \thirdparty\json    <<-- git submodule to https://github.com/nlohmann/json
     \include\
     \src\
     CMakeLists.txt

在您的项目CMakeLists.txt

...
project(mySuperApp)

set(mySuperApp_SRC src/main.c)

# can under some conditions...
add_subdirectory(thirdparty/json)

add_executable(${PROJECT_NAME} ${mySuperApp_SRC})
target_link_libraries(${PROJECT_NAME} PRIVATE nlohmann_json::nlohmann_json)

答案 2 :(得分:1)

它允许您使用 find_packageadd_subdirectory 添加库,并为两者使用相同的目标名称:

# creates nlohmann_json::nlohmann_json
find_package(nlohmann_json REQUIRED)

if (nlohmann_json_NOT_FOUND)
    # creates nlohmann_json AND nlohmann_json::nlohmann_json
    add_subdirectory(thirdparty/json)
endif()

add_executable(your_target_name ${your_target_sources})
target_link_libraries(your_target_name PRIVATE nlohmann_json::nlohmann_json)

如果没有别名,您需要:

# creates nlohmann_json::nlohmann_json
find_package(nlohmann_json REQUIRED)

if (NOT nlohmann_json_FOUND)
    # creates only nlohmann_json
    add_subdirectory(thirdparty/json)
endif()

add_executable(your_target_name ${your_target_sources})
if (nlohmann_json_FOUND)
    target_link_libraries(your_target_name PRIVATE nlohmann_json::nlohmann_json)
else()
    target_link_libraries(your_target_name PRIVATE nlohmann_json)
endif()

答案 3 :(得分:0)

没有别名,您仍然可以通过add_subdirectory添加库,但是在target_link_libraries命令中,您需要省略名称空间:

project(mySuperApp)

set(mySuperApp_SRC src/main.c)

add_subdirectory(thirdparty/json)

add_executable(${PROJECT_NAME} ${mySuperApp_SRC})
target_link_libraries(${PROJECT_NAME} PRIVATE nlohmann_json)

如果您这样做了,但随后决定使用find_package来包含库(而不是add_subdirectory),则需要更改target_link_libraries以使用命名空间目标,即

project(mySuperApp)

set(mySuperApp_SRC src/main.c)

find_package(nlohmann_json REQUIRED)

add_executable(${PROJECT_NAME} ${mySuperApp_SRC})
target_link_libraries(${PROJECT_NAME} PRIVATE nlohmann_json::nlohmann_json)

通过添加别名,使用命名空间版本(即nlohmann_json::nlohmann_json)的target_link_libraries在两种情况下都可以工作,并且如果您以后决定从find_package切换到add_subdirectory,则无需更改)。

相关问题