You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

CMake官方版本号与配置头文件教程示例编译失败,请求原因排查

CMake构建错误:Cannot specify include directories for target "Tutorial" which is not built by this project

我正在遵循CMake官方教程,学习添加版本号和配置头文件的操作。我创建了两个目录:Step1和Step1_build。Step1目录下包含CMakeLists.txt、TutorialConfig.h.in和tutorial.cxx三个文件,各文件内容如下:

CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
# set the project name
project(Tutorial VERSION 1.0)
# configure a header file to pass the version number to the source code
configure_file(TutorialConfig.h.in TutorialConfig.h)
# add directory to list of paths to search for include files
target_include_directories(Tutorial PUBLIC "${PROJECT_BINARY_DIR}" )
# add the executable
add_executable(Tutorial tutorial.cxx)

TutorialConfig.h.in

// the configured options and settings for Tutorial
#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@

tutorial.cxx

#include "TutorialConfig.h"
#include <iostream>
int main(int argc, char *argv[]) {
    if (argc < 2) {
        std::cout << argv[0] << "Version" << Tutorial_VERSION_MAJOR << "." << Tutorial_VERSION_MINOR << std::endl;
        return 1;
    }
    std::cout << "argc=" << argc << std::endl;
    std::cout << "argv[1]=" << argv[1] << std::endl;
}

执行cmake -S Step1 -B Step1_build命令进行构建时,出现以下错误:

CMake Error at CMakeLists.txt:10 (target_include_directories)
Cannot specify include directories for target "Tutorial" which is not built by this project

反复核对教程步骤仍未找到问题,请问该项目无法编译的原因是什么?


问题原因与解决方案

这个错误的核心是CMake命令的执行顺序搞反了:你在调用target_include_directories给目标设置包含目录时,Tutorial这个可执行目标还没被创建出来。

CMake的逻辑是很直白的——所有针对某个目标的配置命令(比如target_include_directoriestarget_link_libraries这类),必须在目标被定义之后才能调用。你的代码里把target_include_directories写在了add_executable前面,此时CMake根本不知道Tutorial这个目标存在,自然会报错。

修正后的CMakeLists.txt

只需要把add_executable的位置提前到target_include_directories之前就行:

cmake_minimum_required(VERSION 3.10)
# set the project name
project(Tutorial VERSION 1.0)
# configure a header file to pass the version number to the source code
configure_file(TutorialConfig.h.in TutorialConfig.h)
# add the executable
add_executable(Tutorial tutorial.cxx)
# add directory to list of paths to search for include files
target_include_directories(Tutorial PUBLIC "${PROJECT_BINARY_DIR}" )

调整后,CMake先通过add_executable创建了Tutorial目标,后续的target_include_directories就能正确找到这个目标并配置包含目录了。

内容的提问来源于stack exchange,提问作者user32882

火山引擎 最新活动