我在使用CMake构建一个项目时遇到了问题。我已经缩小了问题的范围,并在单个.cpp文件中重新创建了它。这个问题是在我尝试将一个项目链接到GTest上时出现的。我知道std::__throw_bad_array_new_length()
不是我通常会调用的东西,下面发布的错误与我在代码中添加测试块时收到的错误相同。我可以使用CMake的fetchcontent将所有的GTest文件拉到我的项目中,但是当我实际尝试在任何.cpp文件中包含一个测试块时,我得到了下面的错误。直接用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)
--编辑g++的输出--版本
$ 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编译的
文件结构以防万一
ProjectDir | CMakeLists.txt | main.cpp |内部版本
发布于 2021-10-27 18:26:08
在深入研究生成的make文件之后,CMake似乎填充了许多链接器和编译器标志,其中许多是不需要的,或者根本就是错误的。在CMake中手动设置链接器和编译器标志已解决此问题。
https://stackoverflow.com/questions/69741498
复制相似问题