"'命名空间'之前的预期不合格ID"错误

wro*_*ame 8 c++ debugging namespaces

我有以下看似无害的代码:

#ifndef UI_H
#define UI_H

#include <string>

namespace ui
{
    //Displays the main menu, showing loaded vocabulary cards
    //
    //Returns upon completion of display
    void displayMainMenu();

    //...More code like the above, just comments followed by functions
}

#endif
Run Code Online (Sandbox Code Playgroud)

这给了我这个错误信息:

filepath/ui.h:6: error: expected unqualified-id before 'namespace'
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

Dav*_*men 19

追踪此类错误的一种方法是从头开始:

#include "filepath/ui.h"
int main () { return 0; }
Run Code Online (Sandbox Code Playgroud)

这会编译吗?(这适用于你提供的ui.h的小片段.)

像这样的错误通常是由于某些先前的类声明中缺少分号引起的.所以让我们试着强迫这个问题:

struct Foo { int foo; } // Note the missing semicolon after the close brace.

#include "filepath/ui.h"
int main () { return 0; }
Run Code Online (Sandbox Code Playgroud)

这当然不能编译干净.我得到一个从我的testmain.cpp到你的filepath/ui.h到string的复杂的包含路径跟踪......最终得到

/usr/include/i386/_types.h:37: error: two or more data types in declaration of '__int8_t'
Run Code Online (Sandbox Code Playgroud)

所以这不是错误,但丢失的分号肯定会造成混乱.你的错误不会出现在内部<string>,所以让我们#include <string>在尝试重新创建错误之前制作我们的测试程序:

#include <string>
struct Foo { int foo; } // Note the missing semicolon after the close brace.

#include "filepath/ui.h"
int main () { return 0; }
Run Code Online (Sandbox Code Playgroud)

并且错误消息是

In file included from testmain.cpp:5:
filepath/ui.h:6: error: expected unqualified-id before 'namespace'
Run Code Online (Sandbox Code Playgroud)

它就是.因此,在filepath/ui.h之前#include的其他一些头文件具有格式错误的类声明.

附录
有时使用不同的编译器会有所帮助.g ++以其对这种常见编程错误的不良处理而臭名昭着.用clang收益率编译上面的内容

testmain.cpp:4:2: error: expected ';' after struct
Run Code Online (Sandbox Code Playgroud)

所以,tada,clang已经把注意力集中在这个问题上.

发生的事情是,当编译器遇到麻烦时,它会对代码应用一些修复,使其在语法上正确.编译器错误消息基于此自动更正.注意:这种自动更正通常是一件非常好的事情.没有它,编译器必须在第一个错误时关闭.由于程序员不可避免地会犯一个以上的错误,一次一个地追捕它们将是后方的痛苦.

我没有最愚蠢的想法,用于修复丢失的分号问题的goofy更正g ++,除了它不添加明显缺少的分号.clang添加了缺少的分号,这就是它所抱怨的.