【问题标题】:CMake Error: "add_subdirectory not given a binary directory"CMake 错误:“add_subdirectory 未给出二进制目录”
【发布时间】:2018-10-28 17:01:10
【问题描述】:

我正在尝试将 Google Test 集成到更大项目的子项目中,但我找不到令我满意的解决方案。

我有两个限制:

  • Google Test 的源代码已经在项目结构中的某个位置(因此不能使用 URL 从 git 存储库下载它)
  • Google Test 的源代码不是我的子项目的子目录(永远不会)

所以当我尝试做这样的事情时:

add_subdirectory( ${GOOGLETEST_PROJECT_LOCATION})

我收到了:

CMake Error at unit_tests/CMakeLists.txt:10 (add_subdirectory):
  add_subdirectory not given a binary directory but the given source
  directory "${GOOGLETEST_PROJECT_LOCATION}" is not a subdirectory of
  "${UNIT_TEST_DIRECTORY}".  When
  specifying an out-of-tree source a binary directory must be explicitly
  specified.

另一方面,ExternalProject_Add 可能是一个解决方案,但当我根本不想下载源代码并使用项目中特定位置的源代码时,我不知道该如何使用它。

项目结构看起来更像这样:

3rdparty 
    |--googletest 
...
subproject
   |--module1
      |--file1.cpp
      |--CMakeLists.txt
   |--module2
      |--file2.cpp
      |--CMakeLists.txt
   |--include
      |--module1
          |--file1.h
      |--module2
          |--file2.h
   |--unit_test
       |--module1
           |--file1test.cpp
       |--module2
           |--file2test.cpp
       |--CMakeLists.txt
   |--CMakeLists.txt
CMakeLists.txt

【问题讨论】:

    标签: c++ build cmake googletest


    【解决方案1】:

    错误消息很清楚 - 您还应该为 googletest 指定 构建目录

    # This will build googletest under build/ subdirectory in the project's build tree
    add_subdirectory( ${GOOGLETEST_PROJECT_LOCATION} build)
    

    当您将 relative 路径(作为 source 目录)提供给 add_subdirectory 调用时,CMake 会自动为 build使用相同的相对路径> 目录。

    但是在绝对源路径的情况下(并且当这个路径不在你的源代码树中时),CMake无法猜测build目录,你需要提供它明确

    对于add_subdirectory 命令,另请参见documentation

    【讨论】:

    • ../Lib1 对 CMake 来说是绝对的吗?因为拥有这种相对路径也会产生这个错误。我认为相对路径可以不包含 bin 目录!
    • 在我的回答帖子中,源路径还有另一个条件 - “当此路径不在您的源树中时” - 当 CMake 需要明确指定构建目录时。也就是说,如果您从 top CMakeLists.txt 调用 add_subdirectory(../Lib1),CMake 将发出有关“未给出二进制目录”的错误。另请注意,应避免在顶级构建目录之外使用构建目录。
    【解决方案2】:

    我觉得有义务对此发表评论,因为这是我在谷歌上搜索此错误时的热门搜索结果。

    对我来说,我显然是个白痴:我已经修改了我项目的 src 目录中的 CMakeLists.txt 文件,但我没有意识到该文件已被锁定并且 VS Code 甚至没有实际保存当我按下 Ctrl+S 时。检查 VS Code 中的文件选项卡,看看那里是否有一个白点,表示文件未保存。按 Ctrl+S 并查看右下角是否有弹出窗口提示您以超级用户身份重试。

    我仍然有错误,但它们是对我的项目有意义的新错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 2013-02-23
      相关资源
      最近更新 更多