【问题标题】:-lpthread linking error [duplicate]-lpthread 链接错误 [重复]
【发布时间】:2012-11-27 04:50:12
【问题描述】:

可能重复:
undefined reference to pthread_create in linux (c programming)

有以下程序:

void *thread(void *vargp);

int main() {
  pthread_t tid;

  pthread_create(&tid, NULL, thread, NULL);
  exit(0);
}

/* thread routine */
void *thread(void *vargp) {
  sleep(1);
  printf("Hello, world!\n");
  return NULL;
}

我应该纠正它。我已经添加了左侧的包含:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

但我仍然收到以下错误:

/tmp/ccHwCS8c.o: In function `main':
1.c:(.text+0x29): undefined reference to `pthread_create'
collect2: ld returned output state 1

我尝试像答案所说的那样在编译器中添加-lpthread,但我仍然得到这个错误代码:

@lap:~$ gcc -Wall -lpthread 1.c -o uno

/tmp/ccl19SMr.o: In function `main':
1.c:(.text+0x29): undefined reference to `pthread_create'
collect2: ld returned exit state 1

【问题讨论】:

    标签: c multithreading


    【解决方案1】:

    您需要使用-lpthread 标志对其进行编译,以便将libpthread 链接到您的可执行文件。

    您还应该添加pthread_join() 函数以让您的主线程等待新线程结束。在您当前的代码中,您不会看到Hello World,因为主线程结束将导致所有子线程退出。

    【讨论】:

    【解决方案2】:

    您需要在编译时明确提及-pthread 选项。 没有这个链接器就无法找到 pthread 库的引用。 这样做:

    gcc -Wall -pthread test.c -o test.out

    【讨论】:

      【解决方案3】:

      在您的编译/链接中添加“-lpthread”。

      【讨论】:

      • 我尝试了gcc -Wall -pthread uno.c -o uno 仍然无法正常工作
      • @Rkan:我是-lpthread
      猜你喜欢
      • 1970-01-01
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 2010-11-24
      相关资源
      最近更新 更多