请帮助编译这个程序

时间:2010-11-10 15:39:16

标签: c linux pthreads

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

void *WriteNumbers(void *threadArg)
{
 int start, stop;
 start = atoi((char *)threadArg);
 stop = start + 10;

 while(start<stop)
 {
  printf("%d\n", start++);
  sleep(1);
 }
}

int main(int argc, char **argv)
{
 pthread_t thread1, thread2;

 // create the threads and start the printing 
 pthread_create(&thread1, NULL, WriteNumbers, (void *)argv[1] );
 pthread_create(&thread2, NULL, WriteNumbers, (void *)argv[2]);

 pthread_join(thread1, NULL);
 pthread_join(thread2, NULL);

 return 0;
}

gcc -o pthread pthread.c 
/tmp/cckJD3rd.o: In function `main':
pthread.c:(.text+0x7a): undefined reference to `pthread_create'
pthread.c:(.text+0xa2): undefined reference to `pthread_create'
pthread.c:(.text+0xb6): undefined reference to `pthread_join'
pthread.c:(.text+0xca): undefined reference to `pthread_join'
collect2: ld returned 1 exit status

5 个答案:

答案 0 :(得分:8)

您需要将-pthread标志添加到编译器中。

答案 1 :(得分:5)

您没有包含pthread库。尝试添加

-lpthread 

到您的赞美行。

答案 2 :(得分:1)

您没有使用libpthread进行链接。用gcc手动编译真的是BFI。将您的代码放在名为'thread_test.c'的文件中,然后执行:

make thread_test LDFLAGS = -lpthread

假设您的代码中没有错误(我没有检查),这应该可以解决您的问题......

答案 3 :(得分:0)

将-pthread添加到gcc命令行。

答案 4 :(得分:0)

像这样:

   gcc -o pthread pthread.c  -lpthread