undefined reference pthread_create

时间:2017-03-02 14:55:53

标签: c undefined-reference

我想弄清楚一个程序:

#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是程序中早期创建的函数。我收到以下错误:

seed@ubuntu:~/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构造函数的格式。我是否需要在主要上方实际定义它?我的印象是它是随图书馆导入的。

我还冒昧地猜测它与第四个参数有关?我理解第一个参数是线程的位置(上面定义),第二个是NULLed,第三个是函数调用,但我不太明白第四个参数应该是什么。

怎么了?

1 个答案:

答案 0 :(得分:0)

所有代码导入都是pthread库的标头。 (pthread.h)

缺少的是链接器需要实际包含gcc的库,需要参数-pthread(在gcc的参数列表的末尾。)

它需要在最后,因为链接器按照命令行中给出的顺序处理参数,如果目标文件尚未处理,则链接器不会有任何未解析的引用尝试通过浏览解析pthread库。

即。这是错误的:

gcc -g -o myprogram -lpthread myprogram.o

这是正确的:

gcc -g -o myprogram myprogram.o -lpthread