14

我似乎在使用CMake-I中的命令设置包含路径 ()时遇到问题。include_directories()我的项目目录如下:

Root
| - CMakeLists.txt
| - libs
| - | - CMakeLists.txt
| - | - inc
| - | - | - // lib specific includes
| - | - src
| - | - | - // lib specific sources
| - proj1
| - | - CMakeLists.txt
| - | - inc
| - | - | - // proj1 specific includes
| - | - src
| - | - | - // proj1 specific sources

CMakeLists.txt文件如下所示:

project(ROOT)
add_subdirectory(libs)
add_subdirectory(proj1)

下的CMakeLists.txt文件libs

project(lib)
add_library(lib STATIC ${lib_hdrs} ${lib_srcs}) // for conciseness, omitted set() 

最后,CMakeLists.txt下的文件proj1

project(proj1)

include_directories("${ROOT_SOURCE_DIR}/lib/inc") # <- problem line?

add_executable(proj1 ${proj1_srcs})
target_link_libraries(proj1 lib)

目标是从 libs 中的源文件和头文件创建库,然后链接到 proj1 下生成的可执行文件。Proj1 有一些文件#include包含在 libs 中,所以我需要添加要与-I. 根据文档,这include_directories()就是应该做的。然而,尽管明确设置并在其后加上 debug message(${INCLUDE_DIRECTORIES}),但该INCLUDE_DIRECTORIES变量是一个空字符串,并且没有为包含路径指定目录,因此我的 proj1 编译失败。

我还尝试删除周围的引号${ROOT_SOURCE_DIR}/inc,看看是否有帮助,但没有运气。

4

1 回答 1

19

include_directories()填充一个名为的目录属性INCLUDE_DIRECTORIES

http://www.cmake.org/cmake/help/v2.8.12/cmake.html#prop_dir:INCLUDE_DIRECTORIES

请注意,CMake 2.8.11 学习了target_include_directories填充INCLUDE_DIRECTORIES目标属性的命令。 http://www.cmake.org/cmake/help/v2.8.12/cmake.html#command:target_include_directories

另请注意,您可以使用关键字将“要针对目标的标头进行编译,需要lib包含目录”这一事实编码到目标本身。lib/inclibtarget_include_directoriesPUBLIC

add_library(lib STATIC ${lib_hdrs} ${lib_srcs}) # Why do you list the headers?
target_include_directories(lib PUBLIC "${ROOT_SOURCE_DIR}/lib/inc")

另请注意,我假设您不安装lib库供其他人使用。在这种情况下,您需要为构建位置和安装位置指定不同的头目录。

target_include_directories(lib
  PUBLIC
    # Headers used from source/build location:
    "$<BUILD_INTERFACE:${ROOT_SOURCE_DIR}/lib/inc>"
    # Headers used from installed location:
    "$<INSTALL_INTERFACE:include>"     
)

无论如何,这仅在您安装lib供他人使用时才重要。

target_include_directories(lib ...)上述之后,您不需要其他include_directories()电话。目标“lib告诉” proj1 它需要使用的包含目录。

另见target_compile_defintions()target_compile_options()

于 2013-10-19T15:14:15.853 回答