CMake中include_directories的使用
Posted fengbingchun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CMake中include_directories的使用相关的知识,希望对你有一定的参考价值。
CMake中include_directories命令用于在构建(build)中添加包含目录,其格式如下:
include_directories([AFTER|BEFORE] [SYSTEM] dir1 [dir2 ...])
将给定的目录添加到编译器(compiler)用于搜索包含文件的目录。相对路径被解释为相对于当前源目录。
包含目录被添加到当前CMakeLists文件的INCLUDE_DIRECTORIES目录属性中。它们也被添加到当前CMakeLists文件中每个目标的INCLUDE_DIRECTORIES目标属性(target property)中。目标属性值是生成器(generator)使用的属性值。
默认情况下,指定的目录被追加到当前目录列表中。这个默认行为可以通过将CMAKE_INCLUDE_DIRECTORIES_BEFORE设置为ON来改变。通过显式使用AFTER或BEFORE,可以在appending和prepending之间进行选择,而不依赖于默认值。
如果给出了SYSTEM选项,编译器将被告知在某些平台上目录是系统包含目录。
include_directories的参数可以使用语法为"$<...>"的"生成器表达式(generator expressions)".
注意:最好使用target_include_directories命令向单个目标添加包含目录,并可选地将它们传播/导出(propagate/export)到依赖项.
执行测试代码需要多个文件:
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)
usage()
echo "Error: $0 needs to have an input parameter"
echo "supported input parameters:"
for param in $params[@]; do
echo " $0 $param"
done
exit -1
if [ $# != 1 ]; then
usage
fi
flag=0
for param in $params[@]; do
if [ $1 == $param ]; then
flag=1
break
fi
done
if [ $flag == 0 ]; then
echo "Error: parameter \\"$1\\" is not supported"
usage
exit -1
fi
if [[ ! -d "build" ]]; then
mkdir build
cd build
else
cd build
fi
echo "==== 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
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_include_directories.cmake内容如下:
message("#### test_$TEST_CMAKE_FEATURE.cmake ####")
include_directories($CMAKE_CURRENT_SOURCE_DIR/include)
add_executable(sample_add $CMAKE_CURRENT_SOURCE_DIR/source/add.cpp $CMAKE_CURRENT_SOURCE_DIR/samples/sample_add.cpp)
另外还包括三个目录:include,source,samples,它们都是非常简单的实现,仅用于测试,如下:
可能的执行结果如下图所示:
如果将test_include_directories.cmake中的include_directories命令注释掉,执行则会报找不到头文件的error:
GitHub: https://github.com/fengbingchun/Linux_Code_Test
以上是关于CMake中include_directories的使用的主要内容,如果未能解决你的问题,请参考以下文章
C++学习(二七一)CMake设置Include目录INCLUDE_DIRECTORIES
CMake 目标 INTERFACE_INCLUDE_DIRECTORIES 是不是自动添加到父 INCLUDE_DIRECTORIES?
如何修复创建使用 PRIVATE include_directories 的库的 cmake 配置