2017-03-02 6 views
0

私はプログラムの意味を理解しようとしています:未定義の参照のpthread_create

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <pthread.h> 

int main(int argc, char** argv) { 

volatile double fShared = 0.0; 
// create pthread structures - one for each thread 
pthread_t t0; 
pthread_t t1; 
//Arbitrary pointer variables - void* is a pointer to anything 
void *thread_res0; 
void *thread_res1; 
int res0,res1; 
//create a new thread AND run each function 
// we pass the ADDRESS of the thread structure as the first argument 
// we pass a function name as the third argument - this is known as a FUNCTION pointer 
// you might want to look at the man pages for pthread_create 
res0 = pthread_create(&t0, NULL, do_this, (void*)""); 
res1 = pthread_create(&t1, NULL, do_that, (void*)""); 
// Two threads are now running independently of each other and this main function 
// the function main is said to run in the main thread, so we are actually running 

// The main code can now continue while the threads run - so we can simply block 
res0 = pthread_join(t0, &thread_res0); 
res1 = pthread_join(t1, &thread_res1); 

printf ("\n\nFinal result is fShared = %f\n",fShared); 
return (EXIT_SUCCESS); 
} 

do_thisとdo_thatは、以前のプログラムで作成した関数であることに留意されたいです。次のエラーが表示されています。

[email protected]:~/Programs$ Homework2OS.c 
/tmp/cceiRtg8.O: in function 'main' 
Undefined reference to 'pthread_create' 
Undefined reference to 'pthread_create' 
Undefined reference to 'pthread_join' 
Undefined reference to 'pthread_join' 

このコードを修正するためのコードがありました。私は他の場所でpthread_createコンストラクタのフォーマットを見つけました。私は実際にメインの上にそれを定義する必要がありますか?私はそれが図書館で輸入されたという印象を受けました。

私は4番目のパラメータと関係があると思いますか?最初のパラメータはスレッドの位置(上で定義したもの)、2番目はNULL、3番目は関数呼び出しですが、4番目のパラメータが何を想定しているのかよく分かりません。

どういうところが間違っていますか?

+0

あなたのコンパイルコマンド、およびあなたの '#のinclude'ディレクティブを表示します。いくつかの[pthread tutorial](https://computing.llnl.gov/tutorials/pthreads/)を読んでください。あなたのオペレーティングシステムは何ですか? [pthread_create(3)]を読んでください(http://man7.org/linux/man-pages/man3/pthread_create.3.html) –

+1

はコンパイラに '-lpthread'オプションを渡します – StoryTeller

+3

実際に' -pthread'を渡すべきですあなたの 'gcc'コンパイラに' -lpthread'ライブラリがリンクされます –

答えて

0

すべてのコードのインポートは、pthreadライブラリのヘッダーです。 (pthread.hの)

何が欠けているが、リンカが-pthreadが必要とされているパラメータをgccのためのライブラリが含まれ、実際にする必要がある(GCCへのパラメータのリストの最後に。)

それはであることが必要リンカはコマンドラインで指定された順序でパラメータを処理し、オブジェクトファイルがまだ処理されていない場合、リンカがpthreadライブラリを参照して解決しようとする未解決の参照はありません。

I.E.これは間違っている:

gcc -g -o myprogram -lpthread myprogram.o 

これは正しいです:

gcc -g -o myprogram myprogram.o -lpthread