对 mq 函数的未定义引用
Undefined references to mq functions
我需要用 C 语言编写的函数 mq_close 的简单示例。
mq_close() 关闭消息队列描述符mqdes.
成功时 mq_close() returns 0;出错时,返回 -1,并设置 errno 以指示错误。
#include <stdio.h>
#include <fcntl.h>
#include <mqueue.h>
int main(int argc, char *argv[])
{
mqd_t mq; // message queue
struct mq_attr ma; // message queue attributes
int status = 0;
int a = 5;
int b = 0;
printf("a = %d, b = %d\n", a, b);
// Specify message queue attributes.
ma.mq_flags = 0; // blocking read/write
ma.mq_maxmsg = 16; // maximum number of messages allowed in queue
ma.mq_msgsize = sizeof(int); // messages are contents of an int
ma.mq_curmsgs = 0; // number of messages currently in queue
// Create the message queue with some default settings.
mq = mq_open("/test_queue", O_RDWR | O_CREAT, 0700, &ma);
// -1 indicates an error.
if (mq == -1)
{
printf("Failed to create queue.\n");
status = 1;
}
if (status == 0)
{
status = mq_send(mq, (char *)(&a), sizeof(int), 1);
status = mq_receive(mq, (char *)(&b), sizeof(int), NULL);
}
if ((status == 0) && (mq_close(mq) == -1))
{
printf("Error closing message queue.\n");
printf("Error deleting message queue.\n");
status = 1;
}
printf("a = %d, b = %d\n", a, b);
return status;
}
错误:
undefined reference to `mq_open'
undefined reference to `mq_send'
undefined reference to `mq_receive'
undefined reference to `mq_close'
undefined reference to `mq_unlink'
Linux 对我来说是个新手,一般来说我是操作系统的初学者。你能解释一下为什么这段代码无法编译吗?
根据手册页https://man7.org/linux/man-pages/man3/mq_open.3.html,您需要
Link with -lrt.
即
gcc mq.c -lrt
我需要用 C 语言编写的函数 mq_close 的简单示例。
mq_close() 关闭消息队列描述符mqdes.
成功时 mq_close() returns 0;出错时,返回 -1,并设置 errno 以指示错误。
#include <stdio.h>
#include <fcntl.h>
#include <mqueue.h>
int main(int argc, char *argv[])
{
mqd_t mq; // message queue
struct mq_attr ma; // message queue attributes
int status = 0;
int a = 5;
int b = 0;
printf("a = %d, b = %d\n", a, b);
// Specify message queue attributes.
ma.mq_flags = 0; // blocking read/write
ma.mq_maxmsg = 16; // maximum number of messages allowed in queue
ma.mq_msgsize = sizeof(int); // messages are contents of an int
ma.mq_curmsgs = 0; // number of messages currently in queue
// Create the message queue with some default settings.
mq = mq_open("/test_queue", O_RDWR | O_CREAT, 0700, &ma);
// -1 indicates an error.
if (mq == -1)
{
printf("Failed to create queue.\n");
status = 1;
}
if (status == 0)
{
status = mq_send(mq, (char *)(&a), sizeof(int), 1);
status = mq_receive(mq, (char *)(&b), sizeof(int), NULL);
}
if ((status == 0) && (mq_close(mq) == -1))
{
printf("Error closing message queue.\n");
printf("Error deleting message queue.\n");
status = 1;
}
printf("a = %d, b = %d\n", a, b);
return status;
}
错误:
undefined reference to `mq_open'
undefined reference to `mq_send'
undefined reference to `mq_receive'
undefined reference to `mq_close'
undefined reference to `mq_unlink'
Linux 对我来说是个新手,一般来说我是操作系统的初学者。你能解释一下为什么这段代码无法编译吗?
根据手册页https://man7.org/linux/man-pages/man3/mq_open.3.html,您需要
Link with -lrt.
即
gcc mq.c -lrt