【问题标题】:why do we need "-pthread" flag to compile a c file [duplicate]为什么我们需要“-pthread”标志来编译c文件[重复]
【发布时间】:2023-03-14 20:32:01
【问题描述】:

我尝试编译一个包含线程的 c 文件。但我试图像这样编译正常的方式

gcc -o thread thread.c -Wall

但它给出了一个错误。但我试图这样编译

gcc -pthread -o 线程 thread.c -Wall

成功了。这是什么原因和 -pthread 标志会做什么? 下面是我的 C 代码

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

void *thread_function(void *arg)
{
    int a;
    for(a=0;a<10; a++)
    {
    printf("Thread says hi!\n");
    sleep(2);
    }
    return NULL;
}

int main(void)
{
    pthread_t mythread;
    if ( pthread_create( &mythread, NULL, thread_function, NULL) )
    {
        printf("error creating thread.");
        abort();
    }
    if ( pthread_join ( mythread, NULL ) )
    {
    printf("error joining thread.");
    abort();
    }
    printf("Main thread says hi!\n");
    exit(0);
}

【问题讨论】:

  • 你应该看看:stackoverflow.com/questions/23250863/…。本质上,您需要告诉编译器在 pthread 库中链接
  • gcc 文档有什么特别不清楚的地方?
  • 阅读本文以供参考https://randu.org/tutorials/threads/
  • 其实 -pthread 和 -lpthread 都是平台相关的。一些标准 C 库,例如 Android Bionic,提供了 pthread_create() 等的内部实现。如果我没有帮助,请阻止我;)
  • 我没有看到这些链接。有很多关于这个错误的链接。我检查了其中一些我没有得到答案。上面的链接给出了正确的答案谢谢你帮助我

标签: c multithreading gcc


【解决方案1】:

没有-pthread 也可以编译

gcc -c thr.c

但它不会链接。要使其链接,您需要 -lpthread 或 -pthread。

gcc thr.c -pthread

仅使用链接标志 (-lpthread) 就足够了(请参阅 -pthread, -lpthread and minimal dynamic linktime dependencies )。

【讨论】:

    【解决方案2】:

    根据gcc参考:

    -pthreads

    使用 POSIX 线程库添加对多线程的支持。这 选项为预处理器和链接器设置标志。这个选项 不影响生成的目标代码的线程安全 编译器或随附的库的编译器。

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 1970-01-01
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 2022-12-06
      相关资源
      最近更新 更多