定义两个源时如何防止 GNU 特定功能

How to prevent GNU-specific function when defined two sources

我需要通过 F_SETPIPE_SZ 使用 fcntl 的 FIFO 大小更改 属性。为此,我需要使用 #define _GNU_SOURCE。但是,我的代码还涉及 strerror_r 功能。通常,我使用它的 XSI-compliant,但是当我添加 #define _GNU_SOURCE 时,它会自动给出以下固有错误,因为它更喜欢使用 GNU 的 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

出于同样的原因,我需要对其他 declarations/definitions 使用 #define _DEFAULT_SOURCE。当我使用以下两个

时,如何使用 XSI-compliant strerror_r
#define _GNU_SOURCE
#define _DEFAULT_SOURCE

How can I use XSI-compliant strerror_r instead

使用所需的 strerror 版本创建一个单独的源文件:

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

创建头文件xsi_strerror.h,函数声明:

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

然后在使用 fcntl 的源文件中使用你的函数:

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

将两个文件一起编译。