2

我已经阅读并尝试了几乎每个教程/wiki/SO 帖子、页面、片段,我可以找到让这个 CMAKE 工作......

我有一个超级简单的目录结构:

ROOT/
|- CMakeLists.txt
|- main.cpp
|- sub/
    |-CMakeLists.txt
    |-subx/
        |-CMakeLists.txt
        |-subx.h
        |-subx.cpp
    |-suby/
        |-CMakeLists.txt
        |-suby.h
        |-suby.cpp

main.cpp 是一个超级简单的 cpp 程序:

//omitting all unnecessary code
int main() {
    subx s;
    s.defined_method();
    s.another_defined_method(1);
    return 0;
}

您可以假设 subx 和 suby 定义是正确的并且工作得很好,因为当我手动编译时它们会这样做。

当我通过 CMake 编译时,出现以下错误:

"/path/to/cmake" --build /path/to/Debug --target CS220_Project -- -j 4
Linking CXX executable simple_project
Undefined symbols for architecture x86_64:
  "subx::defined_method()", referenced from:
      _main in main.cpp.o
  "subx::another_defined_method(int)", referenced from:
      _main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [simple_project] Error 1
make[2]: *** [CMakeFiles/simple_project.dir/all] Error 2
make[1]: *** [CMakeFiles/simple_project.dir/rule] Error 2
make: *** [simple_project] Error 2

根 CMakeLists.txt 文件看起来:

cmake_minimum_required(VERSION 2.8.4)
project(simple_project)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES main.cpp)

add_subdirectory(sub)

add_executable(simple_project ${SOURCE_FILES})

子 CMakeLists.txt 文件看起来:

add_subdirectory(subx)
add_subdirectory(suby)

subx & suby CMakeLists.txt 文件看起来:(它们包括各自的区别)

set(SUBX_SOURCES subx.cpp)

#Add any files in this directory
add_executable(SUBX ${SUBX_SOURCES})

我已经尝试过诸如 add_library、file (glob) 之类的东西。我一辈子都无法获取任何子目录中的文件以使用 main.cpp 程序进行编译。

4

1 回答 1

5

取决于您希望子项目的具体内容。我理解它的方式subxsuby库,应该链接到主可执行文件:

ROOT/CMakeLists.txt

cmake_minimum_required(VERSION 2.8.4)
project(simple_project)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES main.cpp)

add_subdirectory(sub)

add_executable(simple_project ${SOURCE_FILES})
target_link_libraries(simple_project SUBX SUBY)

ROOT/subx/CMakeLists.txt

set(SUBX_SOURCES subx.cpp)

#Add any files in this directory
add_library(SUBX ${SUBX_SOURCES})

(dtto 为suby)

于 2014-10-16T21:08:17.123 回答