为什么这段代码在没有语法错误的情况下无法编译?

0 c c++ gcc compiler-errors syntax-error

我的代码中有一个问题,需要很长时间才能修复它

  • 错误信息 :

初始化程序周围缺少大括号 [-Werror=missing-braces]

    struct entry {
       char *lexptr;
       int token;  
       };
    struct entry keywords[] = {
            "div", DIV,
            "mod", MOD,
            "if", IF,
            "while", WHILE,
            "then", THEN,
            "do", DO,
            "begin", BEGIN,
            "end", END,
                0, 0
        };
Run Code Online (Sandbox Code Playgroud)

当我搜索时,我发现https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25137中有一个异常,但在我的情况下如何修复它?

我认为这是一个小小的改变,但我没有得到它。

Ted*_*gmo 7

错误信息 :
missing braces around initializer [-Werror=missing-braces]

事实上这并不是一个真正的错误。这是一个警告,表明您已通过编译器选项变成了错误。

您可以通过在应该填充的每一对周围添加大括号来修复它entry:

struct entry keywords[] = {
    {"div", DIV},
    //...
};
Run Code Online (Sandbox Code Playgroud)

但是,由于大括号省略,您的代码实际上是完全合法的......在 C 中。

对于 C++ 来说,你不能char*在字符串文字上表达观点。您需要将 的定义更改entry为:

struct entry keywords[] = {
    {"div", DIV},
    //...
};
Run Code Online (Sandbox Code Playgroud)

这样,它在 C++ 中也是合法的:

struct entry {
    const char *lexptr;  // note: const char*
    int token;
};
Run Code Online (Sandbox Code Playgroud)