c - 没有引用 pthread_mutex_lock 编译 -lpthread

标签 c pthreads mutex linker-errors undefined-reference

我正在编译一个程序,该程序包含来自 pthread 库的互斥信号量,但是当我使用 -lpthread 标志进行编译时,我收到 undefined reference 错误。

gcc -lpthread prodcon.c
/tmp/ccESOlOn.o: In function `producer':
prodcon.c:(.text+0x2e): undefined reference to `pthead_mutex_lock'
prodcon.c:(.text+0xd6): undefined reference to `pthead_mutex_unlock'
collect2: ld returned 1 exit status

互斥锁的语法如下:

pthread_mutex_t mutex1;

是一个全局声明,因此它可以被多个线程使用。在我这样调用互斥锁的函数中:

pthead_mutex_lock(&mutex1);
pthead_mutex_unlock(&mutex1);

但是我遇到了编译器错误,我也尝试使用 -pthread 标志进行编译

gcc -pthread prodcon.c
/tmp/cc6wiQPR.o: In function `producer':
prodcon.c:(.text+0x2e): undefined reference to `pthead_mutex_lock'
prodcon.c:(.text+0xd6): undefined reference to `pthead_mutex_unlock'
collect2: ld returned 1 exit status

我已经搜索了答案,但不知所措,如果能帮助我在包含互斥锁的库中进行链接时弄清楚为什么它具有 undefined reference ,我将不胜感激。

最佳答案

顺序很重要,所以使用:

gcc prodcon.c -lpthread 

或者更好:

gcc -Wall -Wextra -pedantic -pthread prodcon.c -lpthread

你确定你使用了pthead_mutex_lock吗?或者这是一个错字?无论如何,它应该是 pthread_mutex_lockpthread_mutex_unlock 也是如此。

关于c - 没有引用 pthread_mutex_lock 编译 -lpthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35716010/

相关文章:

c - 没有得到想要的输出。有人可以告诉我解决方案吗?

c++ - 优化阻塞队列实现的建议

c++ - 线程构建 block 与 pthreads 相结合

go - 为什么互斥锁最终会出现线程正在休眠的错误?

c - try-lock 互斥调用与 CAS 调用

c++ - pthread_cond_wait/signal 和 mutex 未按预期工作

c - 如何在c中保留小数

c - 局部变量的运行时内存分配在嵌入式系统中如何工作?

c - fscanf 函数在预期为 9 时返回 -1

c - Pthread 运行时错误