每次我在 include_directory() 中添加新目录时,Cmake 都会重新编译所有内容

Cmake recompiles everything each time I add a new directory in include_directory()

(这个问题与this one I asked非常相似,但与GLOB的微妙之处无关。所以我认为将这两个问题分开会更清楚)

每次我在 CMakeLists.txt 中添加或删除 include_directory() 中的文件夹(甚至是空的),然后键入

cmake .
make

触发整个项目重新编译。为什么以及我能做些什么?

我的实际 CMakeLists.txt(注意没有 GLOB):

cmake_minimum_required(VERSION 2.8)
cmake_policy(VERSION 2.8.12.2)

# Project
get_filename_component(ProjectName MyProject NAME)
project(${ProjectName})

# Compiler and options
set(CMAKE_CXX_COMPILER /usr/bin/clang++)
set(CLANG_COMPILE_FLAGS "-std=c++1y -stdlib=libc++ ")

# Type of build
set(CMAKE_BUILD_TYPE "Release")
# Build tool 
set(CMAKE_GENERATOR "Unix Makefiles")

set(EXECUTABLE_OUTPUT_PATH ../bin/${CMAKE_BUILD_TYPE})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CLANG_COMPILE_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${CLANG_LINK_FLAGS}")

include_directories(
    [all folders containing .h files here] # adding anything here triggers the whole project to recompile
)

add_executable(
    ${ProjectName}
    [all .cpp and .h files here]
)

命令 include_directories 添加编译器标志(例如 -I/path/to/include/dir 用于 gcc)。因此,如果您更改 include_directories => 编译器标志更改 => 需要重建目标。

例子

为避免定期重新编译整个项目,您需要不要经常修改 include_directories。例如,您可以这样组织代码:

CMakeLists.txt
Source/
        - A/foo.hpp
        - A/foo.cpp
        - B/boo.hpp
        - B/boo.cpp

CMakeLists.txt的内容:

include_directories(./Source)
add_executable(myexe A/foo.hpp A/foo.cpp B/boo.hpp B/boo.cpp)

C++ 文件的内容:

#include "A/foo.hpp"
#include "B/boo.hpp"