I would like to use the same enum in both the client and server parts of my current (C++) project, but am unsure of the proper way to do this. I could easily just write the enu
Putting it in a header file seems reasonable, and wrapping it in a namespace can be useful too. Something i find myself doing with enums is
contents of whatevsenum.hpp:
namespace whatevs
{
enum Enum
{
FOO = 0,
BAR,
BLARGH,
MEH,
SIZE
};
} // namespace whatevs
and then whenever i need to use it in a header/source file elsewhere:
#include "whatevsenum.hpp"
void do_something_with(whatevs::Enum value)
{
// do stuff
}
...
do_something_with(whatevs::FOO);
tl;dr:
Put it in a header file (*.h) and #include
the header file wherever you need to use the enum.
note: this applies to the new (C++11) enum classes as well.
Using a namespace isn't necessary. Including a header file (NOT a .cpp file) in multiple places is common and necessary in most cases. Header files should only include function/method declarations and type definitions as a general rule (this includes class definitions, struct definitions, and yes, enum
definitions). Template functions and methods also need to be defined (not just declared) in a header file.
The other thing to remember about header files is that you should always use an include guard to avoid multiple definitions.
This FAQ may help, but probably will not be sufficient if you need a more complete introduction to C++
Declarations:
void foo(int bar); //Goes in a header file
class argle;
Definitions:
// Put this in a .cpp file
int foo(int bar) {
return bar - 42;
};
// Put this in a header file
template<type T>
int baz(T t) {
return 42;
}
// Put this in a header file
struct bargle {
int fizz;
char *whizz;
}
EDIT:
Found this, it should help you with understanding what to put in which file(s). In fact, this whole wikibook looks like a good resource for a C++ learner: http://en.wikibooks.org/wiki/C%2B%2B_Programming