为什么我们需要“-pthread”标志来编译一个c文件

时间:2017-09-04 13:28:54

标签: c multithreading gcc

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

  

gcc -o thread thread.c -Wall

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

  

gcc -pthread -o thread 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);
}

2 个答案:

答案 0 :(得分:1)

根据gcc参考:

  

<强> -pthreads

     

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

答案 1 :(得分:-2)

它编译时没有-pthread就好了

gcc -c thr.c

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

gcc thr.c -pthread

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

相关问题