Home > Software engineering >  Undefined references to mq functions
Undefined references to mq functions

Time:03-18

I need simple example of function mq_close in C programming language.

mq_close() closes the message queue descriptor mqdes.

On success mq_close() returns 0; on error, -1 is returned, with errno set to indicate the error.

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

ERRORS:

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 is new to me, and I'm beginner in operating systems in general. Could you explain me why this code can't compile?

CodePudding user response:

As per the man page https://man7.org/linux/man-pages/man3/mq_open.3.html you need to

Link with -lrt.

ie

  gcc mq.c -lrt
  • Related