带有包含路径和源路径的 CMake - 基本设置

问题描述 投票:0回答:3

我正在尝试建立一个看起来像我自己的项目的测试项目,只是为了让事情首先正常工作,它看起来像这样:

/MainProject/inc/main.h
/MainProject/src/main.cpp
/LibProject/inc/test.h
/LibProject/src/test.cpp

我找到了一些教程,但是当我有 inc 和 src 文件夹时,我无法找到如何设置它? CMakeLists.txt 文件看起来如何?我会在 / 中各有一个,每个项目文件夹中各有一个吗?好像inc和src文件夹里不需要有一个?

c++ cmake
3个回答
156
投票

每个源子目录都需要一个

CMakeLists.txt
。你的结构应该是这样的:

root
|-MainProject
| |-inc
| | '-main.h
| |-src
| | |-main.cpp
| | '-CMakeLists.txt
| '-CMakeLists.txt 
|-LibProject
| |-inc
| | '-test.h
| |-src
| | |-test.cpp
| | '-CMakeLists.txt
| '-CMakeLists.txt
'-CMakeLists.txt

root/CMakeLists.txt
的内容:

project(MyProject)
add_subdirectory(MainProject)
add_subdirectory(LibProject)

LibProject/CMakeLists.txt
MainProject/CMakeLists.txt
的内容:

add_subdirectory(src)

LibProject/src/CMakeLists.txt
的内容:

# Notice name prefix of this variable, set by CMake according
# to value given with "project()" in the root CMakeLists.txt.
include_directories(${MyProject_SOURCE_DIR}/LibProject/inc)
add_library(LibProject test.cpp)

MainProject/src/CMakeLists.txt
的内容:

include_directories(${MyProject_SOURCE_DIR}/MainProject/inc)
# I assume you want to use LibProject as a library in MainProject.
include_directories(${MyProject_SOURCE_DIR}/LibProject/inc)
link_directories(${MyProject_SOURCE_DIR}/LibProject/src)
add_executable(MainProject main.cpp)
target_link_libraries(MainProject LibProject)

然后配置并构建:

$ cd root
$ mkdir build
$ cd build
$ cmake ..
$ make

35
投票

您可以通过以下方式进行:

  • MainProject 目录中的 CMakeLists.txt:

    project(MainProject)
    
    add_subdirectory(LibProject/src)
    add_subdirectory(MainProject/src)
    
  • LibProject/src 目录中的 CMakeLists.txt:

    include_directories(${PROJECT_SOURCE_DIR}/LibProject/inc/)
    add_library(LibProject test.cpp)
    
  • MainProject/src 目录中的 CMakeLists.txt:

    include_directories(${PROJECT_SOURCE_DIR}/MainProject/inc/)
    add_executable(MainProject main.cpp)
    target_link_libraries(MainProject LibProject)
    

31
投票

就我而言,我想用一个单个 CMakeList 来完成它。这对我有用。我添加我的解决方案,以防它对某人有用。

这就是我在我的案例中所做的:

My structure:
Project
|CMakeLists.txt
|-src
| |*.cpp
| |*.c
|-include
| |*.hpp
| |*.h

我的 CMakeLists.txt 必须有主要部分:

include_directories(
        ${PROJECT_SOURCE_DIR}/include
        ${PROJECT_SOURCE_DIR}/src
)

^ 允许 .cpp 文件在包含文件夹中添加标头。

file(GLOB all_SRCS
        "${PROJECT_SOURCE_DIR}/include/*.h"
        "${PROJECT_SOURCE_DIR}/include/*.hpp"
        "${PROJECT_SOURCE_DIR}/src/*.cpp"
        "${PROJECT_SOURCE_DIR}/src/*.c"
        )

^ 只需添加这些文件夹中的任何内容即可。

add_executable(MyTarget ${all_SRCS})

^ 从所有源列表中构建目标

PS:如果您想查看完整的 CMakeLists.txt,请转到项目链接 NEGU93/ForbiddenDesert

© www.soinside.com 2019 - 2024. All rights reserved.