C++ struct错误的重新定义,我只定义了一次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15042470/
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
Redefinition of struct error, I only defined it once
提问by eveo
I really don't understand how to fix this redefinition error.
我真的不明白如何解决这个重定义错误。
COMPILE+ERRORS
编译+错误
g++ main.cpp list.cpp line.cpp
In file included from list.cpp:5:0:
line.h:2:8: error: redefinition of astruct Linea
line.h:2:8: error: previous definition of astruct Linea
main.cpp
主程序
#include <iostream>
using namespace std;
#include "list.h"
int main() {
int no;
// List list;
cout << "List Processor\n==============" << endl;
cout << "Enter number of items : ";
cin >> no;
// list.set(no);
// list.display();
}
list.h
列表.h
#include "line.h"
#define MAX_LINES 10
using namespace std;
struct List{
private:
struct Line line[MAX_LINES];
public:
void set(int no);
void display() const;
};
line.h
行.h
#define MAX_CHARS 10
struct Line {
private:
int num;
char numOfItem[MAX_CHARS + 1]; // the one is null byte
public:
bool set(int n, const char* str);
void display() const;
};
list.cpp
列表.cpp
#include <iostream>
#include <cstring>
using namespace std;
#include "list.h"
#include "line.h"
void List::set(int no) {}
void List::display() const {}
line.cpp
行.cpp
#include <iostream>
#include <cstring>
using namespace std;
#include "line.h"
bool Line::set(int n, const char* str) {}
void Line::display() const {}
回答by juanchopanza
You need to put include guardsin your headers.
你需要在你的头文件中加入包含守卫。
#ifndef LIST_H_
#define LIST_H_
// List.h code
#endif
回答by Cyrille Ka
In list.cpp, you are including both "line.h" and "list.h". But "list.h" already includes "line.h" so "list.h" is actually included twice in your code. (the preprocessor is not smart enough to not include something it already has).
在 list.cpp 中,您同时包含“line.h”和“list.h”。但是“list.h”已经包含“line.h”,因此“list.h”实际上在您的代码中包含了两次。(预处理器不够聪明,无法包含它已有的东西)。
There are two solutions:
有两种解决方案:
- Do not include "list.h" directly in your list.cpp file, but it is a practice that does not scale: you have to remember what every of your header file includes and that will be too much very quickly.
- use include guards, as explained by @juanchopanza
- 不要在你的 list.cpp 文件中直接包含“list.h”,但这是一种无法扩展的做法:你必须记住你的每个头文件包含的内容,这会很快太多。
- 使用包括守卫,正如@juanchopanza 所解释的
回答by Mats Petersson
You are including "line.h" twice, and you don't have include guards in your header files.
您包含两次“line.h”,并且您的头文件中没有包含保护。
If you add something like:
如果您添加如下内容:
#ifndef LINE_H
#define LINE_H
... rest of header file goes here ...
#endif
to your header files, it will all work out fine.
到你的头文件,一切都会好起来的。