Search code examples
cgcccompilationc-preprocessorpreprocessor

How to prevent GNU-specific function when defined two sources


I need to use fcntl's FIFO size alteration property by using F_SETPIPE_SZ. To do that I need to use #define _GNU_SOURCE. However, my code also involves strerror_r function. Normally, I use XSI-compliant of it but when I add #define _GNU_SOURCE it automatically gives an error inherently the following since it prefers to use GNU's strerror_r.

error: initialization makes integer from pointer without a cast [-Werror=int-conversion]
         int error_num = strerror_r(errno, ERROR_MESSAGE_BUFF, ERROR_MESSAGE_LENGTH);
                         ^~~~~~~~~~
cc1: all warnings being treated as errors

Due to the same reason I need to use #define _DEFAULT_SOURCE as well for other declarations/definitions. How can I use XSI-compliant strerror_r instead when I use the following two

#define _GNU_SOURCE
#define _DEFAULT_SOURCE

Solution

  • How can I use XSI-compliant strerror_r instead

    Create a separate source file with the needed strerror verssion:

    #include <string.h>
    int xsi_strerror_r(int errnum, char *buf, size_t buflen) {
       return strerror_r(errnum, buf, buflen);
    }
    

    Create a header file xsi_strerror.h with function declaration:

    #include <stddef.h>
    int xsi_strerror_r(int errnum, char *buf, size_t buflen);
    

    Then use in your source file that uses fcntl use your function:

    #define _GNU_SOURCE
    #include <fcntl.h>
    #include "xsi_strerror.h"
    int main() {
        if (fcntl(...)) {
            int error_num = xsi_strerror_r(errno, ERROR_MESSAGE_BUFF, ERROR_MESSAGE_LENGTH);
        }
    }
    

    Compile both files together.