列挙型をヘッダーファイルに入れ、それを使用#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などを参照してください。