Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way to share an enum across multiple files?

Tags:

c++

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 enum in it's own file and include that in both files, but that feels like it's poor practice. Would putting it in a namespace and then including it in both be the right way to do it?

I know this is a bit subjective, if there's a better place for "best practice" questions please direct me to it.

Edit (elaboration): I'm sending data from the client to the server and in this case I'd like tell the client about changes in state. However, I'd like to avoid sending all of the information that makes up a state every time I'd like to change it, instead I want to just send a number that refers to an index in an array. So, I figure the best way to do this would be with an enum, but I need the same enum to be on both the client and server so that they both understand the number. Hope that makes sense.

like image 681
rofer Avatar asked May 26 '11 02:05

rofer


People also ask

Should enums be in a separate file?

If the enum is only used within one class, it should be placed within that class, but if the enum is used between two or more classes, it ought to either be in it's own code file, or in a conglomerated code file that contains all the enum for a particular assembly.

How do I use enum in another file?

You have to put the enum in a header file, and use #include to include it in the source file.

Do enums go in header files?

Your code (e.g. your enum) SHOULD be placed in the . h file if you need to expose it to the code you're including the . h file. However if the enum is only specific to the code in your header's .

How many values can enum hold?

An ENUM column can have a maximum of 65,535 distinct elements.


1 Answers

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);
like image 129
Vusak Avatar answered Sep 20 '22 13:09

Vusak