CMake 错误: "add_subdirectory not given a binary directory"

CMake Error: "add_subdirectory not given a binary directory"

本文关键字:given binary directory not 错误 add CMake subdirectory      更新时间:2023-10-16

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

我有两个约束:

  • Google Test的源代码已经在项目结构中的某个地方(因此使用URL从git存储库下载它不是一种选择(
  • 谷歌测试的源代码不是我的子项目的子目录(也永远不会(

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

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

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

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

为调用提供相对路径(作为目录(add_subdirectory时,CMake 会自动对生成目录使用相同的相对路径。

但是在绝对源路径的情况下(当此路径不在源树中时(,CMake 无法猜测构建目录,您需要明确提供它:

另请参阅有关add_subdirectory命令的文档。

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

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

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