【发布时间】:2015-02-17 19:58:30
【问题描述】:
注意:这个问题已经被here间接回答了
问题不在于包括警卫:他们不会帮助跨越不同的 翻译单位
注意:我知道解决方案是使用extern 关键字。
我是 C++ 新手。我在理解头文件中的#ifndef 时遇到问题。当我执行这样的操作时,我收到一条错误消息,指出变量 game_over 和 turn 已定义。
/*chess.h*/
#ifndef CHESS
#define CHESS
#include <iostream>
#include "chessboard.h"
using namespace std;
bool game_over;
char turn;
chessboard board;
int main();
#endif
/*bishop.cpp*/
#include "bishop.h"
#include "chess.h"
bishop::bishop(string pos, char color)
{
int x = pos[0] - 97;
int y = pos[1] - 1;
name = "bishop";
this->color = color;
board.add_new(*this);
}
/*chess.cpp*/
#include "chess.h"
int main()
{
...
}
为什么变量在这里定义了两次?我认为第一次包含chess.h 时,定义了CHESS。所以在 bishop.cpp 中,#include "chess.h" 不会做任何事情,因为标题将从 #ifndef CHESS 跳到 #endif。但它显然不是那样工作的。为什么我错了?
【问题讨论】:
-
您是否有任何 other 源文件也与
#include "chess.h"相关联? -
您是否将此文件包含在多个 cpp 文件中?如果是这样,每个人都会有变量声明。
-
是的,我愿意。所以我不明白为什么我们使用#ifndef 如果它不能阻止这个问题的发生?
-
int main(); #endif真的吗? O_o ,,,
标签: c++ redefinition