header antlr cpp 目标部分不允许使用默认参数的外部函数

header section of antlr cpp target does not allow extern functions with default arguments

C++ (g++ 5.4.0) 有一个奇怪的限制。允许第2行,但不允许第4行:

extern yy(int x);
extern yy(int x);  // re-declaration of an extern function is allowed
extern xx(int x, int y=3);
extern xx(int x, int y=3); // but re-declaration of an an extern function with default args is not allowed

(可以使用 -fpermissive 将此错误转换为警告,但也会绕过其他错误,因此使用该编译器标志不是一个好习惯。所以我不使用此标志。)

这个问题出现在antlr的cpp目标代码的header部分。以下 header 代码:

// G.g4:
grammar G;
@parser::header {
extern xx(int x, int y=3);
}

生成为:

// GParser.h:
extern xx(int x, int y=3);
...

// GParser.cpp:
extern xx(int x, int y=3);
#include "GParser.h"
...

我现在绕过了这个错误,re-coding 像这样:

// G.g4:
@parser::header {
#include "GHeader.h"
}

// GHeader.h:
#ifndef GHEADER
#define GHEADER
extern xx(int x, int y=3);
#endif //GHEADER

但是在 antlr4 本身有更好的方法吗?

这不是 GCC 中的限制,而是 C++ 中的限制。

来自this default argument reference

A redeclaration cannot introduce a default for an argument for which a default is already visible (even if the value is the same).

是否需要将这段代码放在@header 动作中?如果没有,您可以使用 other named actions。例如,@parser::definitions 内容仅转到 .cpp。但这是一个仅在 C++ 目标中可用的命名操作。