大约一年前,我问过CMake中的头依赖关系。

我最近意识到,问题似乎是CMake认为这些头文件是项目的外部文件。至少,在生成Code::Blocks项目时,头文件不会出现在项目中(源文件会出现)。因此,在我看来,CMake认为这些头文件是项目的外部,并没有在依赖项中跟踪它们。

在CMake教程中快速搜索只指向include_directories,这似乎不是我想要的…

向CMake发出特定目录包含要包含的头文件,以及生成的Makefile应该跟踪这些头文件的正确方法是什么?


当前回答

首先,使用include_directories()告诉CMake将目录作为-I添加到编译命令行。其次,在add_executable()或add_library()调用中列出头文件。

举个例子,如果你的项目源在src中,你需要include中的头文件,你可以这样做:

include_directories(include)

add_executable(MyExec
  src/main.c
  src/other_source.c
  include/header1.h
  include/header2.h
)

其他回答

首先,使用include_directories()告诉CMake将目录作为-I添加到编译命令行。其次,在add_executable()或add_library()调用中列出头文件。

举个例子,如果你的项目源在src中,你需要include中的头文件,你可以这样做:

include_directories(include)

add_executable(MyExec
  src/main.c
  src/other_source.c
  include/header1.h
  include/header2.h
)

我使用的是CLion,我的项目结构如下:

--main.cpp
--Class.cpp
--Class.h
--CMakeLists.txt

修改前的CMakeLists.txt:

add_executable(ProjectName main.cpp)

修改后的CMakeLists.txt:

add_executable(ProjectName main.cpp Class.cpp Class.h)

通过这样做,程序编译成功。

添加include_directories(“/ /路径”)。

这类似于使用-I/your/path/here/选项调用gcc。

确保在路径周围加上双引号。其他人没有提到这一点,这让我被困了两天。所以这个答案是给那些对CMake非常陌生和非常困惑的人的。

我也有同样的问题。

我的项目目录是这样的:

    --project
    ---Classes
    ----Application
    -----.h and .c files
    ----OtherFolders
    --main.cpp

我在这些文件夹中存放文件的方法是:

    file(GLOB source_files CONFIGURE_DEPENDS
            "*.h"
            "*.cpp"
            "Classes/*/*.cpp"
            "Classes/*/*.h"
    )

    add_executable(Server ${source_files})

这完全奏效了。

你有两个选择。

旧:

include_directories(${PATH_TO_DIRECTORY})

而新的

target_include_directories(executable-name PRIVATE ${PATH_TO_DIRECTORY})

要使用target_include_directories,您需要定义可执行文件- add_executable(executable-name sourcefiles)。

所以你的代码应该是这样的

add_executable(executable-name sourcefiles)
target_include_directories(executable-name PRIVATE ${PATH_TO_DIRECTORY})

你可以在这里阅读更多内容https://cmake.org/cmake/help/latest/command/target_include_directories.html