Transfer enumeration to another file? C ++

First published here, I'm new to C ++ programming, learning it mainly because I want to know it, because it was always interesting how it works, etc.
I am trying to make a simple game using SFML 2.0, my question is:
I have an enumeration, for example:

enum GameState { Menu, Battle, Map, SubMenu, Typing }; 

So, I want to make such a variable using

  GameState State = Menu; 

And then transfer it to another file as

  extern GameState State; 

But I get an error

  error: 'GameState' does not name a type 

How to transfer enumeration to another file? I am trying to do this by making it a global variable in main.cpp and then including it in the header of another file.

+4
source share
2 answers

You must put the enumeration in the header file and use #include to include it in the source file.

Something like that:

gamestate.h file:

 // 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 file:

 #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 file:

 #include <iostream> #include "gamestate.h" int main() { if (State == Menu) std::cout << "State is Menu\n"; } 

Now the global variable State is defined in the gamestate.cpp file, but can be specified in all source files, which includes gamestate.h , thanks to the extern declaration in this file. And even more importantly, the GameState enumeration type is also determined when you include gamestate.h in the source file, so that the error you have about it will not be gamestate.h will disappear.

For the difference between a declaration and a definition, see, for example, fooobar.com/questions/483 / ....

+7
source

The problem is that you have defined what GameState means in one file, but 2 files must know the definition. A typical way to achieve this is to create a header file (with the .h extension) that will be included (using #include) in both source code files (most likely using .cpp) so that it appears in both. This is better than just copying and pasting the definition (to use it elsewhere, you just need the #include statement, if the definition changes, you just change it in the .h file, and every file that includes it gets the changes when it is recompiled).

+1
source

All Articles