2017-09-04 84 views
0

我试着编译一个包含线程的c文件。但我试图编译正常的方式这样为什么我们需要“-pthread”标志来编译c文件

的gcc -o线程thread.c -Wall

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

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

它的工作。这个和-pthread标志的原因是什么? 下面

#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); 
} 
+0

你应该看看:https://stackoverflow.com/questions/23250863/difference-between-pthread-and-lpthread-while-compiling。从本质上讲,你需要告诉编译器链接到pthread库 – Mike

+0

关于gcc文档的特别不清楚? – Olaf

+0

阅读本文以供参考[https://randu.org/tutorials/threads/](https://randu.org/tutorials/threads/) –

回答

0

根据gcc参考:

-pthreads

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

+0

避免回答明显重复请。 –