首页 > 解决方案 > 包含成员函数名称为 errno 和 cerrno 时的 g++7 编译错误

问题描述

主文件

#include <cerrno>

class A { 
public:
    int errno();
};

int A::errno()
{
    return 0;
}

int main()
{
    return 0;
}

用g++编译main.cc报错:

In file included from /usr/include/c++/7/cerrno:42:0,
             from 1.cc:1:
main.cc:8:8: error: expected unqualified-id before ‘(’ token
int A::errno()

但是相同的代码通过 g++6 及以下版本成功编译

以下代码通过 g++7 编译成功

#include <cerrno>

class A { 
public:
    int errno()
    {   
        return 0;
    }   
};

int main()
{
    return 0;
}

那么有什么想法吗?

标签: c++gcccompiler-errorsg++

解决方案


errno是一个宏。引用cppreference

扩展为 POSIX 兼容的线程局部错误号变量的宏

如果您#undef errno在源代码中添加一个,它将编译但不知何故违背了 errno 的目的。
您根本不应该将方法命名为 errno。
要弄清楚为什么它在一种情况下有效,而在另一种情况下无效,您需要扩展errno宏并查看生成的内容。

所以这是输出或编译器尝试编译的内容:

class A {
public:
    int (*__errno_location ())(){return 0;}
};

class A {
public:
    int(*foo()) ();
};
int A::(*__errno_location ())(){return 0;}

推荐阅读