pthread_create的未定义引用错误

8

我有这段代码:

#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库,我无法弄清楚这个错误的原因。


展示一下您如何编译程序。 - cnicutar
你是如何添加链接器选项的?在哪里添加的?使用的是哪个版本的Code::Blocks? - another.anon.coward
可能是Undefined reference to pthread_create in Linux的重复问题。 - 1201ProgramAlarm
5个回答

30

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

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


1
@RamyAlZuhouri 不,你不是。你可能搞砸了代码块的设置。+1 来抵消错误的负评。 - cnicutar
是的,我已放置它。它在设置->编译器和调试器->(编译器设置选项卡)->其他选项中。 - Ramy Al Zuhouri
3
这不正确。它更多是一个链接器设置。所以请做以下操作:设置->编译器和调试器->链接器设置(选项卡)。在"链接库"部分中选择"添加"。添加 pthread 库的路径(很可能是 /usr/lib/libpthread.so)。尝试构建。 - another.anon.coward
此外,如果你尝试过某个方法但未成功,也不应该对其进行负评,同时也没有告诉我们你的问题所在。 - user529758
2
请注意,使用“-pthread”是更可取的,因为在仅安装有“libpthread.a”的系统上,使用“-lpthread”将无法链接。 - e-sushi

15

在没有看到编译器命令的情况下,我怀疑-lpthread不在最后。 库需要放在编译器命令的末尾:

gcc main.c -lpthread

然而,使用-pthread替代-lpthread,因为-pthread可以添加其他设置(例如定义宏_REENTRANT)。


我使用Code::Blocks编译它,在C::B选项中,我现在将“_-lpthread_”改为“_-pthread_”,但没有任何变化。 这是我在设置中唯一的选项。 - Ramy Al Zuhouri
我不熟悉code::blocks,但你能尝试完全重建源代码吗? - hmjd

5
请使用以下命令: gcc -pthread -o main main.c

0
在Eclipse中,您应该添加字符串pthread。
项目->属性->C/C++构建->设置->工具设置->GCC链接器->库->库(-l)->添加->pthread
完成后,您可以构建您的项目。

1
但是OP在评论中说他正在使用Code::Blocks而不是Eclipse。 - Fabio says Reinstate Monica

-2
找到解决方案啦 :D 只需前往 设置 >> 编译器 >> 链接器选项卡 >> 添加库 前往驱动器并进入 lib 文件夹,找到 x86_64_linux_gnu 并找到 pthread 享受吧 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接