gccはpthreadに接続できませんか?

gccはpthreadに接続できませんか?

私は最近XUbuntu 11.10 64ビットをインストールしましたが、最も単純なpthreadの例をコンパイルするのに問題があります。

コードは次のとおりですpthread_simple.c

#include <stdio.h>
#include <pthread.h> 
main()  {
  pthread_t f2_thread, f1_thread; 
  void *f2(), *f1();
  int i1,i2;
  i1 = 1;
  i2 = 2;
  pthread_create(&f1_thread,NULL,f1,&i1);
  pthread_create(&f2_thread,NULL,f2,&i2);
  pthread_join(f1_thread,NULL);
  pthread_join(f2_thread,NULL);
}
void *f1(int *x){
  int i;
  i = *x;
  sleep(1);
  printf("f1: %d",i);
  pthread_exit(0); 
}
void *f2(int *x){
  int i;
  i = *x;
  sleep(1);
  printf("f2: %d",i);
  pthread_exit(0); 
}

コンパイル命令です

gcc -lpthread pthread_simple.c

結果:

lptang@tlp-linux:~/test/test-pthread$ gcc -lpthread pthread_simple.c
/tmp/ccmV0LdM.o: "main" 関数から:
pthread_simple.c:(.text+0x2c): 'pthread_create'への未定義参照
pthread_simple.c:(.text+0x46): 'pthread_create'への未定義参照
pthread_simple.c:(.text+0x57): 'pthread_join'への未定義参照
pthread_simple.c:(.text+0x68): 'pthread_join'への未定義参照
Collect2: ld は 1 つの終了状態を返します。

問題の原因が何であるかを知っている人はいますか?

ベストアンサー1

最新バージョンのgccコンパイラでは、ライブラリはオブジェクトまたはソースファイルに準拠している必要があります。

したがって、コンパイルするには、次のようにする必要があります。

gcc pthread_sample.c -lpthread

通常、pthreadコードは次のようにコンパイルされます。

gcc -pthread pthread_sample.c

おすすめ記事