【问题标题】:Undefined reference to pthread_create对 pthread_create 的未定义引用
【发布时间】:2012-03-21 10:55:10
【问题描述】:

我有这个代码:

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

void* cuoco(void* arg)
{
    fprintf(stderr,"Inizio codice cuoco\n");
    fprintf(stderr,"Fine codice cuoco\n");
    return NULL;
}

void* cameriere(void* arg)
{
    fprintf(stderr,"Inizio codice cameriere\n");
    fprintf(stderr,"Fine codice cameriere\n");
    return NULL;
}

void* cliente(void* arg)
{
    fprintf(stderr,"Inizio codice cliente\n");
    fprintf(stderr,"Fine codice cliente\n");
    return NULL;
}

int main(int argc, char* argv[])
{
    void* (*routine)(void*);
    routine=cuoco;
    pthread_t thread_cuoco,thread_cameriere,thread_cliente;
    pthread_create(&thread_cuoco,NULL,routine,NULL);
    return 0;
}

在编译器选项中我插入 -lpthread
但它说:
“对 pthread_create 的未定义引用”
我使用的是 ubuntu 10.10,所以我已经安装了 pthread 库,我不知道这个错误的原因。

【问题讨论】:

标签: c pthreads


【解决方案1】:

使用 -lpthread 作为最后一个编译器标志。

示例: gcc -o sample sample.c -lpthread

【讨论】:

  • @RamyAlZuhouri 不,你没有。您可能搞砸了代码块设置。 +1 反对错误的反对票。
  • 是的,我已经放了。它在设置->编译器和调试器->(编译器设置选项卡)->其他选项。
  • @RamyAlZuhouri:这是不对的。它更像是一个链接器设置。所以这样做:设置->编译器和调试器->链接器设置(选项卡)。在链接库部分下选择“添加”。添加 pthread 库的路径(很可能是 /usr/lib/libpthread.so)。然后尝试构建
  • 另外,如果您尝试过,您不应该投反对票,但它不起作用,但您也没有告诉我们......
  • 请注意,最好使用-pthread,因为-lpthread 将无法在仅安装libpthread.a 的系统上链接。
【解决方案2】:

没有看到编译器命令,我怀疑-lpthread 没有结束。库需要放在编译器命令的末尾:

gcc main.c -lpthread

但是,请使用-pthread 而不是-lpthread,因为-pthread 可能会添加其他设置(例如定义宏_REENTRANT)。

【讨论】:

  • 我用 code::blocks 编译它,现在在 C::B 选项中我用 -pthread 更改了 -lpthread,但什么都没有改变了。这是我在设置中的唯一选项。
  • 我不熟悉 code::blocks,但是你能尝试完全重建源代码吗?
【解决方案3】:

使用以下命令:

gcc -pthread -o main main.c

【讨论】:

    【解决方案4】:

    在 Eclipse 中,你应该添加字符串 pthread。

    Project -&gt; Properties -&gt; C/C++ Build -&gt; Settings -&gt; Tool Settings -&gt; GCC Linker -&gt; Libraries -&gt; Libraries (-l) -&gt; Add -&gt; pthread

    在此之后,您可以构建您的项目。

    【讨论】:

    • 但是 OP 在评论中说他使用的是 Code::Blocks,而不是 Eclipse。
    【解决方案5】:

    找到解决方案的家伙:D 去settings &gt;&gt; compiler &gt;&gt; linker tab &gt;&gt;add lib

    转到驱动器并转到 lib 文件夹并找到 x86_64_linux_gnu 并找到 pthread 享受:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-03
      • 2013-06-20
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      相关资源
      最近更新 更多