首页 > 解决方案 > CMake 无法链接标准库的部分内容,但手动编译工作正常

问题描述

我在使用 CMake 构建项目时遇到问题。我已经缩小了问题范围并在单个 .cpp 文件中重新创建了它。当我试图将项目与 GTest 链接时,这个问题就开始了。我知道这std::__throw_bad_array_new_length()不是我通常会调用的,下面发布的错误与我在代码中添加 TEST 块时收到的错误相同。我可以使用 CMake 的 fetchcontent 将所有 GTest 文件拉入我的项目,但是当我实际尝试在任何 .cpp 文件中包含 TEST 块时,我会收到以下错误。直接用 g++ 编译单个 .cpp 文件就可以了。我能够构建并运行具有预期结果的输出。但是,使用 CMake 我收到链接器错误。

.cpp 文件。

#include <iostream>

int main() {
    std::cout << "Hello World\n";
    std::__throw_bad_array_new_length()
}

当我手动编译时,这是我的结果:

$ g++ main.cpp 
$ ./a.out
Hello World
terminate called after throwing an instance of 'std::bad_array_new_length'
  what():  std::bad_array_new_length
Aborted (core dumped)

--edit g++ 的输出 --version

$ g++ --version
g++ (Ubuntu 11.1.0-1ubuntu1~18.04.1) 11.1.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

--

这当然是我所期望的。但是,针对 CMake 运行此命令会导致以下结果。

CMakeLists.txt:

cmake_minimum_required(VERSION 3.20)

project(TestProject CXX)

add_executable(MainTest main.cpp)

输出:

build$ cmake ..
-- The CXX compiler identification is GNU 11.1.0
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/g++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: build

build$ make
[ 50%] Building CXX object CMakeFiles/MainTest.dir/main.cpp.o
[100%] Linking CXX executable MainTest
CMakeFiles/MainTest.dir/main.cpp.o: In function `main':
main.cpp:(.text.startup.main+0x1f): undefined reference to `std::__throw_bad_array_new_length()'
collect2: error: ld returned 1 exit status
CMakeFiles/MainTest.dir/build.make:96: recipe for target 'MainTest' failed
make[2]: *** [MainTest] Error 1
CMakeFiles/Makefile2:82: recipe for target 'CMakeFiles/MainTest.dir/all' failed
make[1]: *** [CMakeFiles/MainTest.dir/all] Error 2
Makefile:90: recipe for target 'all' failed
make: *** [all] Error 2

这两个都是用 g++ 11.1 编译的


文件结构以防万一

项目目录 | CMakeLists.txt | 主.cpp | 建造

标签: c++cmakelinkerg++linker-errors

解决方案


在挖掘生成的 make 文件后,似乎 CMake 填充了很多链接器和编译器标志,其中许多是不需要的,或者只是错误的。在 CMake 中手动设置链接器和编译器标志已经解决了这个问题。


推荐阅读