我正在尝试组织一个 C++ 项目,该项目开始有很多文件。我想创建两个使用 Cmake 共享一些源文件的可执行文件。我在这里发现了一个有趣的过程:
下面是我的版本
file(GLOB Common_sources RELATIVE "Common" "*cpp")
file(GLOB Mps_sources RELATIVE "Mps" "*.cpp")                 
file(GLOB Mss_sources RELATIVE "Mss" "*.cpp") 
add_executable(test_mss ${Common_sources} ${Mss_sources}) 
add_executable(test_mps ${Common_sources} ${Mps_sources})
但是 CMake 抱怨
CMake Error at src/CMakeLists.txt:44 (add_executable):
add_executable called with incorrect number of arguments
CMake Error at src/CMakeLists.txt:45 (add_executable):
add_executable called with incorrect number of arguments
说要查看CMakeOutput.log,但是文件实在是太长了,找不到有用的信息。
我检查了 CMake 文档,它似乎可以将第二个源作为附加参数。https://cmake.org/cmake/help/v3.0/command/add_executable.html
我想找到这个错误的来源。我有一种感觉,我在这里遗漏了一些明显的东西。
您得到的错误是因为传递给 的源列表add_executable实际上是空的。
在Common/子目录中收集源的正确方法是:
file(GLOB Common_sources "Common/*.cpp")
在命令file(GLOB) RELATIVE选项中没有指定搜索目录。相反,它只是告诉 CMake 生成相对路径而不是绝对路径:
如果指定了 RELATIVE 标志,则结果将作为给定路径的相对路径返回。
假设
file(GLOB Common_sources "Common/*.cpp")
# gets: /<path-to-source>/Common/my_source.cpp
然后(还要注意RELATIVE 选项中的绝对路径)
file(GLOB Common_sources RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/Common" "Common/*.cpp")
# gets: my_source.cpp
和(当文件不在RELATIVE目录下时)
file(GLOB Common_sources RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/Mps" "Common/*.cpp")
# gets: ../Common/my_source.cpp