What is the correct way to share an enumeration in multiple files?

I would like to use the same enumeration in both the client and server parts of my current (C ++) project, but I'm not sure how to do this. I could just write the listing in its own file and include this in both files, but this seems like bad practice. Putting it in a namespace and then including it in both options would this be the correct way?

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

Change (development): I send data from the client to the server, in which case I would like to inform the client about the state changes. However, I would like to avoid sending all the information that makes up the state every time I would like to change it, instead I just want to send a number that refers to the index in the array. So, I believe that the best way to do this would be with an enumeration, but I need the same enumeration as on the client and on the server so that they both understand the number. Hope this makes sense.

+3
source share
2 answers

Putting it in the header file seems reasonable, and packing it in the namespace can also be useful. Something I do with the listings,

contents of whatevsenum.hpp:

namespace whatevs
{
    enum Enum
    {
        FOO = 0,
        BAR,
        BLARGH,
        MEH,
        SIZE
    };
} // namespace whatevs

, / :

#include "whatevsenum.hpp"

void do_something_with(whatevs::Enum value)
{
    // do stuff
}

...

do_something_with(whatevs::FOO);
+8

TL;DR: (*.h) #include , .

note: (++ 11) .

. ( .cpp ) . / ( , , enum ). ( ) .

, , , include guard, .

FAQ , , , , ++

:

void foo(int bar); //Goes in a header file

class argle;

:

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

this, , (). , wikibook ++: http://en.wikibooks.org/wiki/C%2B%2B_Programming

+8

All Articles