Cmake添加库别名
我正试图弄清楚这个github json项目的cmake文件中的行是什么Cmake添加库别名,cmake,Cmake,我正试图弄清楚这个github json项目的cmake文件中的行是什么 add_library(${NLOHMANN_JSON_TARGET_NAME} INTERFACE) add_library(${PROJECT_NAME}::${NLOHMANN_JSON_TARGET_NAME} ALIAS ${NLOHMANN_JSON_TARGET_NAME}) 特别是在这个例子中,这在这个cmake文件中允许什么,否则是不可能的 在这个CMakeLists.cmake中,我没有看到其他对${
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()使用项目时,它使目标与名称空间一起工作。,使用git的dull函数显示在这个commit中添加了一行:,它附带了以下注释: CMake约定使用项目名称空间,即Foo::,来进行导入 目标。从一个项目导入多个目标时,看起来 类似于Foo::Bar1 Foo::Bar2等,这会将nlohmann_json::名称空间添加到 导出的目标名称 这还允许从中使用生成的项目配置文件 生成目录,而不仅仅是安装目录
这将允许使用
nlohmann/json
项目,方法是将它添加到带有add_子目录(…)的超级项目中
例如,简单的项目结构:
<root project>\
\thirdparty\json <<-- git submodule to https://github.com/nlohmann/json
\include\
\src\
CMakeLists.txt
在没有别名的情况下,您仍然可以通过
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_子目录
相反),则需要更改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\u json::nlohmann\u json
)的目标链接库在任何情况下都可以工作,如果您以后决定从find\u package
切换到add\u子目录
),则无需更改 它允许您添加带有find_package
或add_子目录
的库,这两个目录使用相同的目标名称:
# 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()
谢谢尽管注释掉这一行并再次生成生成,但生成的配置文件的输出是相同的。
# 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()