2017-09-04 83 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

避免回答明顯重複請。 –