![](/img/trans.png)
[英]std::thread, posix threads, and win32 threads in MinGW-W64
[英]How to use std::thread on Windows with MinGW with POSIX threads
我一直在尝试编译并运行以下非常简单的代码
#include <thread>
using namespace std;
void thread_c() {
for (int i = 0; i < 11; ++i) {
cout << i;
}
}
int main()
{
thread t(thread_c);
t.join();
system("pause");
return 0;
}
我正在使用 MinGW 6.3.0(目标 x86_64-w64-mingw32)在 Windows 10 上编译,线程 model(使用g++ -v
获得)是 POSIX。
我没有收到g++ -Wall -g test.cpp -o test.exe
的任何编译错误,但是在尝试运行 exe 时出现运行时错误( entry point of _ZNSt6thread15_M_start_threadESt10unique_ptrINS_3_StateESt14default_deleteIS1_EEPFvve cannot be found
)。
我还尝试使用-pthread
或-lpthread
标志进行编译,但我遇到了相同的运行时错误。 显然这似乎与 std::thread 的使用有关,但我不知道如何解决这个问题。 我是否缺少在 Windows 上启用 POSIX 线程支持的编译标志或附加库?
编辑:我设法通过将编译命令更改为g++ -Wall -g test.cpp -o test.exe -static-libgcc -static-libstdc++ -Wl,-Bstatic -lstdc++ -lpthread -Wl,Bdynamic
在进行必要的修复后,我尝试了您的代码:
#include <thread>
#include <iostream>
using namespace std;
void thread_c() {
for (int i = 0; i < 11; ++i) {
std::cout << i;
}
}
int main()
{
thread t(thread_c);
t.join();
system("pause");
return 0;
}
它工作正常。 构建命令与您的相同:
g++ -Wall -g test.cpp -o test.exe
output 是:
012345678910Press any key to continue . . .
但我确实使用了 MinGW-w64 GCC 12.1.0(来自 https://winlibs.com/ )而不是非常旧的版本 6.3.0。
也许您使用的 MinGW-w64(或者它仍然是旧的 MinGW)库太旧了......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.