c++ - 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 | 建造
解决方案
在挖掘生成的 make 文件后,似乎 CMake 填充了很多链接器和编译器标志,其中许多是不需要的,或者只是错误的。在 CMake 中手动设置链接器和编译器标志已经解决了这个问题。
推荐阅读
- react-native - 使用 react-native-youtube 时如何在代码中静音?
- python - Telethon Python - 将传入消息存储在文件中并回读
- excel - 在 Excel 中使单元格闪烁(宏中的宏)
- flutter - VoidCallback,函数(x),值已更改
, 值设定器 哪一个用于回调?(颤振/飞镖) - javascript - 如何从二维数组中提取列?
- ajax - 通过 ajax 将数据传递给 laravel,包括答案中的数组
- java - Autowired ServletContext 在 xml 定义的 bean 中为 NULL
- python-3.x - 如何将地址转换为地理坐标
- javascript - 如何通过 nuxt-property-decortor 在 Nuxt.js 应用程序中使用 mixins
- java - 仅更改图像的 rgb 值并转换回图像