mingw中的libpthread找不到库 [英] libpthread in mingw does not find the libraries

查看:469
本文介绍了mingw中的libpthread找不到库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用mingw编译以下程序:

I am trying to compile the following program with 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程序. (这只是所有失败程序的简单操作,但基本上所有使用pthreads的程序都会遇到相同的错误,C和C ++)

But with an older version of MingGW I had no problems running pthreads programs. (This is just the simple of all the programs that failed, but basically everything that uses pthreads ends up with the same error, C and C++)

推荐答案

-lpthread移至该命令的末尾:

g++ -ohello.exe hello.cc -lpthread

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

The order of the arguments is important. (Using -pthread throughout instead of -lpthread for linking is actually recommended, since it sets flags both for the preprocessor and the linker.)

这篇关于mingw中的libpthread找不到库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆