为什么这段代码不能用 clang 构建,用 gcc 崩溃,但在 VC++ 上运行良好?

Why this code doesn't build with clang, crashes with gcc, but runs fine with VC++?

本文关键字:但在 崩溃 gcc VC++ 运行 构建 段代码 代码 clang 不能 为什么      更新时间:2023-10-16

此代码:

#include <iostream>
#include <future>
int main()
{
    std::async([]{std::cout << "hellon";}).get();
}

运行良好,使用 Visual C++ 2013 打印hello,但在 gcc 生成时引发异常:

terminate called after throwing an instance of 'std::system_error'
what():  Unknown error -1

甚至不使用 clang 构建,产生以下错误消息:

/usr/bin/ld: /tmp/source-83f28e.o: undefined reference to symbol 'pthread_setspecific@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我使用 rexter 来运行测试。你能解释一下这种行为吗?

编辑

使用-pthread编译器选项,gcc版本运行良好,clang版本现在构建并产生:

hello
exception_ptr not yet implemented

为了添加对多线程的支持,您需要链接到 pthread 库。这是在GCC和Clang上-pthread(作为内置标志提供)。或者,-lpthread可以做到这一点。

相关文章: