cmake-添加子模块

时间:2018-09-07 13:41:38

标签: c++ cmake

我正在尝试使用“子模块/子项目”构建测试项目。

编译失败并显示:

example_01/src/main.cpp:2:10: fatal error: inc/foo2.hpp: No such file or directory
#include "inc/foo2.hpp" // #include "submodule/inc/foo2.hpp"
          ^~~~~~~~~~~~~~
compilation terminated.
make[2]: *** [CMakeFiles/hello_world.dir/build.make:63: CMakeFiles/hello_world.dir/src/main.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:73: CMakeFiles/hello_world.dir/all] Error 2
make: *** [Makefile:84: all] Error 2

我的文件:

主要CMakeLists.txt

cmake_minimum_required(VERSION 3.12)
project(hello_world)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

include_directories(${PROJECT_SOURCE_DIR})
add_subdirectory("submodule")
add_executable(${PROJECT_NAME} 
src/main.cpp 
src/foo.cpp)

main.cpp

#include "inc/foo.hpp"
#include "inc/foo2.hpp" // #include "submodule/inc/foo2.hpp"

int main()
{
    foo();
    foo2();

    return 0;
}

foo.cpp

#include <iostream>
#include "inc/foo.hpp"

void foo()
{
    std::cout << "Hello World!\n";
}

foo.hpp

void foo();

子模块cmakelist

project(submodule_dummy1)
add_executable(${PROJECT_NAME} src/foo2.cpp)

foo2.cpp

#include <iostream>
#include "inc/foo2.hpp"

void foo2()
{
    std::cout << "FuuTwo\n";
}

foo2.hpp

void foo2();

我还需要声明其他内容,以便它可以“看到”子模块头吗?

更新

.
├── build
├── CMakeLists.txt
├── inc
│   └── foo.hpp
├── readme.md
├── src
│   ├── foo.cpp
│   └── main.cpp
└── submodule
    ├── CMakeLists.txt
    ├── inc
    │   └── foo2.hpp
    └── src
        └── foo2.cpp

新的主cmakelist

cmake_minimum_required(VERSION 3.12)
project(hello_world)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

include_directories(${PROJECT_SOURCE_DIR})
include_directories(${PROJECT_SOURCE_DIR}/submodule)

add_subdirectory("submodule")
add_executable(${PROJECT_NAME} 
    src/main.cpp 
    src/foo.cpp)

新错误消息

Scanning dependencies of target hello_world
[ 20%] Building CXX object CMakeFiles/hello_world.dir/src/main.cpp.o
[ 40%] Linking CXX executable hello_world
/usr/bin/ld: CMakeFiles/hello_world.dir/src/main.cpp.o: in function `main':
main.cpp:(.text+0xa): undefined reference to `foo2()'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/hello_world.dir/build.make:99: hello_world] Error 1
make[1]: *** [CMakeFiles/Makefile2:73: CMakeFiles/hello_world.dir/all] Error 2
make: *** [Makefile:84: all] Error 2

1 个答案:

答案 0 :(得分:0)

您缺少一个

include_directories(${PROJECT_SOURCE_DIR}/submodule)

在主CMakeLists.txt中。

此外,您还需要编译和链接submodule/src/foo2.cpp(通过将其作为参数添加到主CMakeLists.txt中的add_executable命令中。