mingw中的libpthread没有找到库

Sam*_*yon 3 mingw pthreads

我试图用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;
}
Run Code Online (Sandbox Code Playgroud)

使用此命令:

g++ -lpthread -ohello.exe hello.cc
Run Code Online (Sandbox Code Playgroud)

我收到以下消息:

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
Run Code Online (Sandbox Code Playgroud)

但是使用较旧版本的MingGW,运行pthreads程序没有问题.(这只是失败的所有程序的简单,但基本上所有使用pthreads的程序都会出现相同的错误,C和C++)

Mat*_*Mat 9

移动-lpthread到该命令的末尾:

g++ -ohello.exe hello.cc -lpthread
Run Code Online (Sandbox Code Playgroud)

参数的顺序很重要.(实际上建议使用-pthread贯穿而不是-lpthread用于链接,因为它为预处理器和链接器设置了标志.)