首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >CMake无法链接标准库的各个部分,但手动编译可以很好地工作

CMake无法链接标准库的各个部分,但手动编译可以很好地工作
EN

Stack Overflow用户
提问于 2021-10-27 15:31:26
回答 1查看 64关注 0票数 1

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

cpp文件。

代码语言:javascript
运行
复制
#include <iostream>

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

当我手动编译时,结果如下:

代码语言:javascript
运行
复制
$ 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++的输出--版本

代码语言:javascript
运行
复制
$ 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:

代码语言:javascript
运行
复制
cmake_minimum_required(VERSION 3.20)

project(TestProject CXX)

add_executable(MainTest main.cpp)

输出:

代码语言:javascript
运行
复制
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 |内部版本

EN

回答 1

Stack Overflow用户

发布于 2021-10-27 18:26:08

在深入研究生成的make文件之后,CMake似乎填充了许多链接器和编译器标志,其中许多是不需要的,或者根本就是错误的。在CMake中手动设置链接器和编译器标志已解决此问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69741498

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档