如何使用CMake从根文件夹外部添加包含目录?

问题描述:

这是我第一次的CMakeLists.txt代码:如何使用CMake从根文件夹外部添加包含目录?

#cmake_minimum_required (VERSION 2.6) 
project (project) 

add_subdirectory(src) 

include_directories(${/path_to_directory}/include) 

而且这是在的CMakeLists.txt子目录

set (CMAKE_C_FLAGS "-WALL -g") 

file(GLOB SRCS *.cpp *.hpp *.h) 

add_executable(source ${SRCS}) 

我仍然无法在自己的项目中path_to_directory

编辑:这也没有工作:

file(GLOB mylib *.cpp *.hpp *.h) 

add_executable(includeSource ${mystuff}) 
target_include_directories(
    mystuff 
    PUBLIC ${path_to_directory}/include 
) 
+0

你是指'$ {path_to_include}/include'而不是'$ {/ path_to_include}/include'?什么'message(“$ {path_to_include}”)'显示?什么'message(“$ {INCLUDE_DIRECTORIES}”)'显示(在执行'include_directories'后)? –

即使问题不清楚,我想你想target_include_directorieshere的文档),而不是include_directories

从文档:

指定包含目录或目标编译给定的目标时使用。

你可以使用它作为:

target_include_directories(
    your_target_name 
    PUBLIC ${/path_to_directory}/include 
) 
+0

我显然是做错了。我想: 文件(GLOB MYLIB *的.cpp * .HPP的* .h) add_executable(includeSource $ {}的MyStuff) target_include_directories( 的MyStuff PUBLIC $ {} path_to_directory /包括 ) – user3063750

+0

我上面贴的代码 – user3063750

根据你的2个码,我理解你的可执行source不能编译,因为编译器不从${/path_to_directory}/include找到包括文件。

在这个假设下,我可以说你错位include_directories(${/path_to_directory}/include),它应该在CMakeLists.txt子目录下。

documentation of include_directories将帮助您了解:

的包括目录添加到当前CMakeLists文件INCLUDE_DIRECTORIES目录属性。它们也被添加到当前CMakeLists文件中每个目标的INCLUDE_DIRECTORIES目标属性中。目标属性值是生成器使用的值。

否则,您可以在主要的CMakeLists.txt通过target_include_directories(source PUBLIC ${/path_to_directory}/include)更换include_directories(${/path_to_directory}/include)为@skypjack建议。它会影响子目录的CMakeLists.txt中的源目标。


其它附加的意见和建议

  1. 要编译C++源文件,但你定义CMAKE_C_FLAGS而不是CMAKE_CXX_FLAGS。

  2. set (CMAKE_C_FLAGS "-Wall -g")如果您以前设置了CMAKE_C_FLAGS,则会很危险。优选set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -g")

  3. file(GLOB ...)不建议找到源文件。See the documentation

我们不建议使用GLOB收集源文件的列表,从你的源代码树。如果在添加或删除源时未更改CMakeLists.txt文件,则生成的生成系统无法知道何时要求CMake重新生成。

  1. 如果你的主要的CMakeLists.txt是为你展示那么简单,add_subdirectory是没用的。你可以只做一个主要的CMakeLists.txt
开始=>