如何修复“函数的隐式声明 'pipe2' 在 C99 中无效”

How to fix 'implicit declaration of function 'pipe2' is invalid in C99'

我正在尝试构建我的库,但是一个名为 evutil.c fom libevent 的文件让我遇到了困难。

libevent/evutil.c: error: implicit declaration of function 'pipe2' is invalid in C99

涉及的代码为:

    if (pipe2(fd, O_NONBLOCK|O_CLOEXEC) == 0)
        return 0;

我现在无法将我的代码更新到 c11。 我应该如何更改代码才能不再出现此错误?

这不是 C99 问题。您需要为 pipe2 添加 header。 According to the pipe2 manualunistd.h.

为什么 libevent 本身不这样做是一个有效的问题。

最上面的manpage

#define _GNU_SOURCE             /* See feature_test_macros(7) */
#include <fcntl.h>              /* Obtain O_* constant definitions */
#include <unistd.h>

您需要 headers 和功能测试宏。

然后标识符应该可用,至少在 Linux/glibc。

示例:

#define _GNU_SOURCE             /* See feature_test_macros(7) */
#include <fcntl.h>              /* Obtain O_* constant definitions */
#include <unistd.h>

int main()
{
    (void)&pipe;
}

您需要包含 header 来声明您正在使用的函数。为了弄清楚您需要哪些 header,您需要查阅函数文档。在 Posix 函数中,最好的来源是 man.

man pipe2 会给你以下内容:

PIPE(2)                    Linux Programmer’s Manual                   PIPE(2)

NAME
       pipe, pipe2 - create pipe

SYNOPSIS
       #include <unistd.h>

       int pipe(int pipefd[2]);

       #define _GNU_SOURCE
       #include <unistd.h>

       int pipe2(int pipefd[2], int flags);

就在那里,在概要中,您将看到所需的 header 个文件。

升级到 C11 不是答案;而是降级到允许隐式声明的 C90(但会产生警告),或者至少使用更宽松的编译器选项进行编译 - 也许 -std=gnu99-std=c90-Wno-implicit 结合使用以抑制警告。

更好的选择是在 evutil.c 中包含适当的 header <unistd.h>,但是您可能不希望修改库代码,在这种情况下您可以使用强制包含编译器选项 -include unistd.h。此 pre-processor 选项将处理源文件文件,就像 #include "file" 出现在第一行一样。