【问题标题】:CMake - add_executable called with incorrect number of argumentsCMake - 使用错误数量的参数调用 add_executable
【发布时间】:2018-05-12 23:14:15
【问题描述】:

我正在尝试组织一个开始有很多文件的 C++ 项目。我想创建两个使用 Cmake 共享一些源文件的可执行文件。我在这里发现了一个有趣的过程:

How to add source files in another folder

下面是我的版本

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 将失败。您可以使用 message ("Common ${Common_sources}") 之类的东西来输出您的来源列表。

标签: c++ cmake


【解决方案1】:

你得到的错误是因为源列表,传递给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

and(当文件不在RELATIVE目录下时)

file(GLOB Common_sources RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/Mps" "Common/*.cpp")
# gets: ../Common/my_source.cpp

【讨论】:

【解决方案2】:

你必须引用变量。

add_executable(test_mss "${Common_sources}" "${Mss_sources}")

否则对于空变量,CMake 将变量替换为空,并且参数的数量似乎是错误的。

类似问题:https://stackoverflow.com/a/39733128/2799037

【讨论】:

  • 引用一个变量的解引用,当变量可以为空的时候,是有意义的,但只有当空字符串是可以接受的时候。在add_executable 的情况下,不接受空字符串(源文件名不能为空)。所以引用与add_executable 无关。
猜你喜欢
  • 1970-01-01
  • 2020-03-29
  • 2014-01-01
  • 2022-09-10
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多