2017-09-04 3 views
0

私はインクルードスレッドであるcファイルをコンパイルしようとしています。しかし、私は-Wallなぜ私は "-pthread"フラグを使ってcファイルをコンパイルする必要がありますか

thread.cこの

のgcc -o糸のような通常の方法をコンパイルしようとしたが、それはエラーが発生します。しかし、私はこの方法のようにそれが働い-Wall

thread.c

のgcc -pthread -oスレッドをコンパイルしようとしました。これと-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/) –

答えて

-1

以下の私のCコードは、それは-pthreadなし

gcc -c thr.c 

罰金をコンパイルしますが、それはリンクしません。リンクを作成するには、-lpthreadまたは-pthreadが必要です。のみ連結フラグ(-lpthread)を使用

gcc thr.c -pthread 

は(-pthread, -lpthread and minimal dynamic linktime dependenciesを参照)に十分であるべきです。

0

gcc文献によれば:

-pthreads

は、POSIXスレッドライブラリを使用してマルチスレッドのサポートを追加します。この オプションは、プリプロセッサとリンカの両方にフラグを設定します。このオプション は、 コンパイラによって生成されたオブジェクトコードのスレッドセーフティまたはそれに付属のライブラリのスレッドセーフティには影響しません。

+0

明白な重複に答えることを控えてください。 –

関連する問題