C语言 为什么即使包含正确的头文件,也会出现“未定义引用”错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4121090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:56:35  来源:igfitidea点击:

Why do I get "undefined reference" errors even when I include the right header files?

cpthreads

提问by Cold-Blooded

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,它声明了这些函数?

回答by James McNellis

You probably forgot to link with the Pthreads library (using -lpthreadon the command line).

您可能忘记链接 Pthreads 库(-lpthread在命令行上使用)。

回答by dreamlax

Others have mentioned that you haven't linked with the pthread library using the -lpthreadflag. 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 库添加对多线程的支持。此选项为预处理器和链接器设置标志。

回答by qrdl

You need to link pthreadlibrary to your binary, like this:

您需要将pthread库链接到您的二进制文件,如下所示:

cc -o myapp myapp.c -lpthread

回答by mohamedkaidi

Do

gcc -pthread -o name filename.c (cpp)

to compile the program, then

编译程序,然后

./name

to run the program.

运行程序。

回答by Shashanoid

For folks looking for the csapp solution. Compile "csapp.c" first, then

对于寻找 csapp 解决方案的人。先编译“csapp.c”,然后

gcc -o filename filename.c csapp.o -lpthread