简体   繁体   English

CMake:C++ 包含相对于基目录

[英]CMake: C++ include relative to base directory

Say I have the following file structure:假设我有以下文件结构:

project/
  - src/
    - main.cpp
    moduleA/
      - moduleA.cpp
      - moduleA.hpp
    moduleB/
      - moduleB.cpp
      - moduleB.hpp

Within moduleB I would like to use moduleA.在 moduleB 中,我想使用 moduleA。 As such, I would like to include moduleA.hpp but as a relative path to src .因此,我想包含moduleA.hpp但作为src的相对路径。 Aka, I would like to be able to write #include moduleA/moduleA.hpp to use moduleA. #include moduleA/moduleA.hpp ,我希望能够编写#include moduleA/moduleA.hpp来使用 moduleA。 I have control over all files, and can put CMakeLists.txt or FindModule<>.cmake in any directories.我可以控制所有文件,并且可以将CMakeLists.txtFindModule<>.cmake放在任何目录中。

Note: I want to do this because there are files in each module that have the same name (in this case, parameters.hpp ).注意:我想这样做是因为每个模块中都有具有相同名称的文件(在本例中为parameters.hpp )。 Therefore, I would like to be able to include parameters.hpp relative to src directory for readability purposes, and to ensure that the correct parameters file is being included.因此,为了便于阅读,我希望能够包含相对于src目录的parameters.hpp ,并确保包含正确的参数文件。

If this is confusing, or any other information is required, please ask.如果这令人困惑,或者需要任何其他信息,请询问。 Thanks for all the help everyone!谢谢各位的帮助!

You can use a structure similar to the following:您可以使用类似于以下内容的结构:

project/
  - CMakeLists.txt
  - src/
    - CMakeLists.txt
    - main.cpp
  - moduleA/
      - CMakeLists.txt
      - moduleA/
          - moduleA.cpp
          - moduleA.hpp
  - moduleB/
      - CMakeLists.txt
      - moduleB/
          - moduleB.cpp
          - moduleB.hpp

with the following files:使用以下文件:


project/CMakeLists.txt : project/CMakeLists.txt

cmake_minimum_required(VERSION 3.0.2)

project(myProject)

add_subdirectory(moduleA)
add_subdirectory(moduleB)
add_subdirectory(src)

project/moduleX/CMakeLists.txt (X = A or B): project/moduleX/CMakeLists.txt (X = A 或 B):

add_library(X STATIC ${moduleX_sources})
# The following line is very practical:
# it will allow you to automatically add the correct include directories with "target_link_libraries"
target_include_directories(X PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

# only in CMakeLists.txt of module B, possibly with PRIVATE instead of PUBLIC
target_link_libraries(X PUBLIC A)

project/src/CMakeLists.txt : project/src/CMakeLists.txt

add_executable(myExe ${exe_sources})
target_link_libraries(myExe A B) # <-- Automatically sets the correct include directories!!

With all this, you can use有了这一切,你可以使用

#include "moduleX/moduleX.hpp"

See here for a similar question and more detailed answer.有关类似问题和更详细的答案,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM