C++ 编译错误“'struct' type redefinition”虽然它是它的第一个定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5825084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compile error "'struct' type redefinition" although it's the first definition for it
提问by Homam
Everything was working well untill I moved some code from the main file to a new class, then I had the following error:
一切正常,直到我将一些代码从主文件移动到一个新类,然后出现以下错误:
error C2011: 'color1' : 'struct' type redefinition
错误 C2011:“color1”:“struct”类型重新定义
struct color1
{
color1()
{
red = green = blue = 0;
}
color1(float _red, float _green, float _blue)
{
red = _red;
green = _green;
blue = _blue;
}
float red, green, blue;
};
Any idea ?
任何的想法 ?
回答by Mark B
If the compiler says it's redefined, then it probably is.
如果编译器说它是重新定义的,那么它可能是。
My psychic debugging skills tell me that you moved the struct from a source file to a header file, and forget the include guards in that header, which is then included multiple times in a source file.
我的通灵调试技巧告诉我,您将结构从源文件移动到头文件,而忘记了该头文件中的包含保护,然后在源文件中多次包含该保护。
EDIT: As a general rule I generally suggest avoiding leading underscores. In some cases (for example followed by a capital letter) they're reserved for the implementation and it's simplest to just never use leading _
instead of hoping you remember all the rules.
编辑:作为一般规则,我通常建议避免使用前导下划线。在某些情况下(例如后跟大写字母),它们是为实现保留的,最简单的是永远不要使用领先_
而不是希望您记住所有规则。
回答by beduin
From snippet above I can't deduce something is wrong.
从上面的片段中,我无法推断出问题所在。
But typically this error means that you are including same header files multiple times. Don't you forget to add standard guards for include files?
但通常此错误意味着您多次包含相同的头文件。你不是忘记为包含文件添加标准保护吗?
#ifndef MY_HEADER_FILE_
#define MY_HEADER_FILE_
// here is your header file code
#endif
回答by Jake OPJ
You can have the definition of the structure on a header file. Have
您可以在头文件上定义结构。有
#pragma once
at the beginning of the header where the struct is defined, it solves the problem.
在定义结构的头文件的开头,它解决了这个问题。
回答by ChrCury78
I had the same problem and luckily did not take long figure out that it was just a silly mistake.
我遇到了同样的问题,幸运的是没有花很长时间就发现这只是一个愚蠢的错误。
The thing was that I had a backup of my project at another drive (D:) but all the code was set on the drive C: when explicitly defined the full path. I created it on the C: path and was always using that way, but accidentally opened the project from the D and thought that it was the same thing, so at compile it was including twice because in some cases it was including the code from the C: path and at others from the D: path.
问题是我在另一个驱动器 (D:) 上备份了我的项目,但是当明确定义完整路径时,所有代码都设置在驱动器 C: 上。我在 C: 路径上创建了它并一直使用这种方式,但不小心从 D 中打开了该项目并认为它是同一件事,因此在编译时它包含两次,因为在某些情况下它包含来自C:路径和其他来自 D:路径。