错误 C2146 的可能原因:语法错误:缺少 ';'在标识符之前
我正在做一个示例应用程序,其中声明了一个结构:
// common.h
typedef struct MyStruct
{
int a;
}
//sample.h
#include "common.h"
int main()
{
MyStruct st;// getting error here
}
C2146:语法错误:缺少“;”在标识符之前
可能的原因是什么?
I am doing a sample application where I have declared a struct:
// common.h
typedef struct MyStruct
{
int a;
}
//sample.h
#include "common.h"
int main()
{
MyStruct st;// getting error here
}
C2146: syntax error : missing ';' before identifier
What are the possible reasons for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有两件事:
首先,结构定义后缺少一个分号:
但这仍然是错误的。您将需要修复其他错误。
其次,您应该像这样定义结构:
或者,您可以这样定义它:
Two things:
First, you're missing a semi-colon after the struct definition:
Not that this is still wrong. You will need to fix the other error.
Second, you should define the struct like this:
Alternatively, you can define it like this:
您的
"common.h"
标头未正确定义MyStruct
;它的末尾需要一个分号。那么
typedef
就是空的;在 C++ 中,您不需要typedef
来定义类型MyStruct
。 (在 C 中,您需要编写:但 C++ 并不要求这样做 - 尽管它也不反对它。)
因此,编写以下内容就足够了:
Your
"common.h"
header does not defineMyStruct
properly; it needs a semi-colon on the end.Then the
typedef
is vacuous; in C++, you don't need thetypedef
to get typeMyStruct
defined. (In C, you'd need to write:But C++ does not require that - though it does not object to it, either.)
So, it would be sufficient to write:
这几乎总是,因为此时尚未定义类型
MyStruct
,要么是因为您包含了错误的标头,要么是类型规范由于某种原因失败。如果该 typedef 与您在 common.h 中的 typedef 完全相同,则它将无法工作。它后面应该跟有别名类型和分号。或者您可能不需要 typedef,因为 C++ 允许您在源代码中将
MyStruct
引用为“正确的”类型。像这样的东西工作得很好:
或者甚至这样,显示了三种可能性:
It's almost always because the type
MyStruct
isn't defined at that point, either because you're including the wrong header or the type specification fails for some reason.If that typedef is exactly what you have in your
common.h
, it won't work. It should be followed by the aliasing type and a semicolon. Or perhaps you didn't want a typedef since C++ allows you to refer toMyStruct
as a "proper" type in the source code.Something like this works fine:
Or even this, showing the three possibilities: