When I tried to compile this program, it failed:
当我尝试编译这个程序时,它失败了:
#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);
}
return 0;
}
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;
}
It gave me the following errors:
它给了我以下错误:
tmp/ccrW21s7.o: In function `main':
pthread.c:(.text+0x83): undefined reference to `pthread_create'
pthread.c:(.text+0xaa): undefined reference to `pthread_create'
pthread.c:(.text+0xbd): undefined reference to `pthread_join'
pthread.c:(.text+0xd0): undefined reference to `pthread_join'
collect2: ld returned 1 exit status
Why does it give me these undefined reference errors even though I had included pthread.h
, which declares these functions?
为什么它给了我这些未定义的引用错误,即使我已经包含pthread.h,它声明了这些函数?
4 个解决方案
#1
24
You probably forgot to link with the Pthreads library (using -lpthread
on the command line).
您可能忘记链接Pthreads库(在命令行上使用-lpthread)。
#2
21
Others have mentioned that you haven't linked with the pthread library using the -lpthread
flag. Modern GCC (not sure how modern, mine is 4.3.3) allows you to use just -pthread
. From the man page:
其他人提到你没有使用-lpthread标志与pthread库链接。现代GCC(不确定现代,我的4.3.3)允许你只使用-pthread。从手册页:
-pthread
Adds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker.-pthread使用pthreads库添加对多线程的支持。此选项为预处理器和链接器设置标志。
#3
3
You need to link pthread
library to your binary, like this:
您需要将pthread库链接到二进制文件,如下所示:
cc -o myapp myapp.c -lpthread
#4
1
Do
做
gcc -pthread -o name filename.c (cpp)
to compile the program, then
然后编译程序
./name
to run the program.
运行程序。
#1
24
You probably forgot to link with the Pthreads library (using -lpthread
on the command line).
您可能忘记链接Pthreads库(在命令行上使用-lpthread)。
#2
21
Others have mentioned that you haven't linked with the pthread library using the -lpthread
flag. Modern GCC (not sure how modern, mine is 4.3.3) allows you to use just -pthread
. From the man page:
其他人提到你没有使用-lpthread标志与pthread库链接。现代GCC(不确定现代,我的4.3.3)允许你只使用-pthread。从手册页:
-pthread
Adds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker.-pthread使用pthreads库添加对多线程的支持。此选项为预处理器和链接器设置标志。
#3
3
You need to link pthread
library to your binary, like this:
您需要将pthread库链接到二进制文件,如下所示:
cc -o myapp myapp.c -lpthread
#4
1
Do
做
gcc -pthread -o name filename.c (cpp)
to compile the program, then
然后编译程序
./name
to run the program.
运行程序。