CMake中的target_sources命令用于将源添加到target,其格式如下:
target_sources( [items1...][ [items2...] ...]) # general formtarget_sources([[FILE_SET [TYPE ] [BASE_DIRS ...] [FILES ...]]...]...) # File Sets
1.指定构建target和/或其依赖项时要使用的源(sources)。命名的
需要INTERFACE, PUBLIC和PRIVATE关键字来指定它们后面的源文件路径(
对相同
允许使用INTERFACE_SOURCES导出targets.
允许在IMPORTED targets上设置INTERFACE项。
相对源文件路径被解释为相对于当前源目录(即CMAKE_CURRENT_SOURCE_DIR)。
以生成器表达式开头的路径保持不变。当target的SOURCE_DIR属性不同于CMAKE_CURRENT_SOURCE_DIR时,在生成器表达式中使用绝对路径以确保将sources正确分配给target。
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
add_library(add STATIC) # 在build目录下会生成libadd.a
target_sources(add PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/source/add.cpp)
2.File Sets: 3.23版本中新增内容。将文件集(file set)添加到target,或将文件添加到现有文件集。target具有零个或多个命名文件集。每个文件集都有name, type, INTERFACE, PUBLIC或PRIVATE范围,一个或多个基本目录以及这些目录中的文件。
可接受的type包括:
(1).HEADERS:通过语言的#include机制使用的源。
(2).CXX_MODULES:实验性的。
(3).CXX_MODULE_HEADER_UNITS:实验性的。
INTERFACE或PUBLIC文件集中的文件可以使用install(TARGETS)命令安装,并使用install(EXPORT)和export命令导出。
每个target_sources(FILE_SET)条目都以INTERFACE, PUBLIC或RIVATE开头,并接受以下参数:
(1).FILE_SET
(2).TYPE
(3).BASE_DIRS
(4).FILES
执行测试代码需要多个文件:
build.sh内容如下:
#! /bin/bash# supported input parameters(cmake commands)
params=(function macro cmake_parse_arguments \find_library find_path find_file find_program find_package \cmake_policy cmake_minimum_required project include \string list set foreach message option if while return \math file configure_file \include_directories add_executable add_library target_link_libraries install \target_sources add_custom_command add_custom_target)usage()
{echo "Error: $0 needs to have an input parameter"echo "supported input parameters:"for param in ${params[@]}; doecho " $0 ${param}"doneexit -1
}if [ $# != 1 ]; thenusage
fiflag=0
for param in ${params[@]}; doif [ $1 == ${param} ]; thenflag=1breakfi
doneif [ ${flag} == 0 ]; thenecho "Error: parameter \"$1\" is not supported"usageexit -1
fiif [[ ! -d "build" ]]; thenmkdir buildcd build
elsecd build
fiecho "==== test $1 ===="# test_set.cmake: cmake -DTEST_CMAKE_FEATURE=$1 --log-level=verbose ..
# test_option.cmake: cmake -DTEST_CMAKE_FEATURE=$1 -DBUILD_PYTORCH=ON ..
cmake -DTEST_CMAKE_FEATURE=$1 ..
# It can be executed directly on the terminal, no need to execute build.sh, for example: cmake -P test_set.cmake
make
# make install # only used in cmake files with install command
CMakeLists.txt内容如下:
cmake_minimum_required(VERSION 3.22)
project(cmake_feature_usage)message("#### current cmake version: ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}.${CMAKE_PATCH_VERSION}")
include(test_${TEST_CMAKE_FEATURE}.cmake)
message("==== test finish ====")
test_target_sources.cmake内容为上面的所有测试代码段。
另外还包括三个目录:include,source,samples,它们都是非常简单的实现,仅用于测试,如下:
可能的执行结果如下图所示:
GitHub: http://github.com/fengbingchun/Linux_Code_Test