您必须将枚举放在头文件中,并用于#include
将其包含在源文件中。
像这样的东西:
文件gamestate.h
:
// These two lines prevents the file from being included multiple
// times in the same source file
#ifndef GAMESTATE_H_
#define GAMESTATE_H_
enum GameState
{
Menu,
Battle,
Map,
SubMenu,
Typing
};
// Declare (which is different from defining) a global variable, to be
// visible by all who include this file.
// The actual definition of the variable is in the gamestate.cpp file.
extern GameState State;
#endif // GAMESTATE_H_
文件gamestate.cpp
:
#include "gamestate.h"
// Define (which is different from declaring) a global variable.
GameState State = Menu; // State is `Menu` when program is started
// Other variables and functions etc.
文件main.cpp
:
#include <iostream>
#include "gamestate.h"
int main()
{
if (State == Menu)
std::cout << "State is Menu\n";
}
现在全局变量在文件State
中定义,但由于该文件中的声明,gamestate.cpp
可以在包含的所有源文件中引用。更重要的是,当您包含在源文件中时,也会定义枚举类型,因此您对它未定义的错误将消失。gamestate.h
extern
GameState
gamestate.h
有关声明和定义之间的区别,请参见例如https://stackoverflow.com/a/1410632/440558。