【问题标题】:Why do I get "undefined reference" errors even when I include the right header files?为什么即使我包含正确的头文件,我也会收到“未定义的引用”错误?
【发布时间】:2010-11-08 03:42:45
【问题描述】:

当我试图编译这个程序时,它失败了:

#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;
}

它给了我以下错误:

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

为什么即使我包含了声明这些函数的pthread.h,它也会给我这些未定义的引用错误?

【问题讨论】:

  • 您还有其他问题:您没有检查argc 的值,但您正在使用argv 的值。您的 WriteNumbers 方法没有返回值。
  • @dreamlax:我修复了“不退货”问题;我没有注意到 argc/argv 问题。

标签: c pthreads


【解决方案1】:

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

【讨论】:

  • 我已将此作为常见问题解答添加到标签 wiki。这个问题在每个秋季学期开始时被问到:)
  • @cold-blooded 你为什么不接受这个答案?
【解决方案2】:

其他人提到您没有使用-lpthread 标志与pthread 库链接。现代 GCC(不确定有多现代,我的是 4.3.3)允许您只使用 -pthread。从手册页:

-pthread
使用 pthreads 库添加对多线程的支持。这 选项为预处理器和链接器设置标志。

【讨论】:

  • 实际上,它是允许这样做的“旧” gcc。 -pthread 是非常古老的语法,仅用于与不支持 -l 的旧编译器兼容...
  • @WouterVerhelst 我认为这不是真的。 -pthread 仍然是推荐使用的标志,因为它还设置任何所需的预处理器和编译标志,而 -lpthread 仅指示链接器链接到 libpthread。
【解决方案3】:

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

cc -o myapp myapp.c -lpthread

【讨论】:

    【解决方案4】:

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

    编译程序,然后

    ./name
    

    运行程序。

    【讨论】:

      【解决方案5】:

      适合寻找 csapp 解决方案的人。先编译“csapp.c”,再编译

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

      【讨论】:

        猜你喜欢
        • 2022-06-10
        • 2021-12-19
        • 1970-01-01
        • 1970-01-01
        • 2020-10-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多