【问题标题】:How to prevent GNU-specific function when defined two sources定义两个源时如何防止特定于 GNU 的功能
【发布时间】:2019-08-19 11:57:53
【问题描述】:

我需要通过F_SETPIPE_SZ 来使用fcntl 的FIFO 大小更改属性。为此,我需要使用#define _GNU_SOURCE。但是,我的代码还涉及strerror_r 函数。通常,我使用它的 XSI 兼容,但是当我添加 #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

出于同样的原因,我也需要将#define _DEFAULT_SOURCE 用于其他声明/定义。当我使用以下两个时,如何使用 XSI-compliant strerror_r 代替

#define _GNU_SOURCE
#define _DEFAULT_SOURCE

【问题讨论】:

  • 如果strerror_r() 出错,你会如何处理error_num?这可能会影响正确的答案。
  • 也许使用#include <linux/fcntl.h> 而不是#define _GNU_SOURCE。或者也许用#define _GNU_SOURCE#undef _GNU_SOURCE包围所有#include <fcntl.h>
  • @AndrewHenle 现在只打印错误消息并退出。但案件可能在未来可能会发生变化
  • 好吧,为了保持未来的灵活性,我认为最好将离群值的调用与其他代码隔离在它自己的单独编译单元中,并提供一个标准中立的包装器。由于您声明您的大部分代码都符合 XSI,我会将 GNU fcntl() 调用本身移动到它自己的文件中,并提供类似 gnu_fcntl() 包装函数的东西。这使得符合 XSI 的代码需要一个 GNU 特定的特性非常明显。
  • @IanAbbott 你能用一个小代码sn-p 显示你提到的后一种用法吗?

标签: c gcc compilation c-preprocessor preprocessor


【解决方案1】:

如何改用符合 XSI 的 strerror_r

使用所需的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);
    }
}

一起编译这两个文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多