我正在尝试使用 mingw 编译以下程序:
#include <pthread.h>
#include <errno.h>
#include <unistd.h>
#include <iostream>
#include <cstdio>
void *hello(void *id) {
int nid = *static_cast<int*>(id);
std::printf("Hello from thread %d\n", nid);
return 0;
}
int main(int argc, char **argv) {
pthread_t ids[2];
int *params[2];
for (int i = 0; i < 2; ++i) {
params[i] = new int;
*params[i] = i;
pthread_create(&ids[i], 0, hello, params[i]);
}
for (int i = 0; i < 2; ++i)
pthread_join(ids[i], 0);
for (int i = 0; i < 2; ++i)
delete params[i];
return 0;
}
使用这个命令:
g++ -lpthread -ohello.exe hello.cc
我收到以下消息:
C:\Users\XXXXXX~1\AppData\Local\Temp\cczPlv0w.o:hello.cc:(.text+0xad): undefined
reference to `_imp__pthread_create'
C:\Users\XXXXXX~1\AppData\Local\Temp\cczPlv0w.o:hello.cc:(.text+0xe9): undefined
reference to `_imp__pthread_join'
collect2: ld returned 1 exit status
但使用旧版本的 MingGW 时,我运行 pthreads 程序没有任何问题。 (这只是所有失败的程序中最简单的一个,但基本上所有使用 pthread 的程序都会出现相同的错误,C 和 C++)
Move -lpthread
到该命令的末尾:
g++ -ohello.exe hello.cc -lpthread
参数的顺序很重要。 (使用-pthread
整个而不是-lpthread
实际上建议使用 for 链接,因为它为预处理器和链接器设置标志。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)