In C
you can make enumerations like this:
enum {
key_1 = 1,
key_2 = 2,
key_3 = 4
};
The problem that I have found is, when you place this in a public header, you cannot ensure that the values in the pre compiled implementation do match with the public header. For example:
enum lvls {
debuglvl_debug = 0x01
debuglvl_info = 0x02,
debuglvl_warning = 0x04,
debuglvl_error = 0x08,
/* And so on... */
debuglvl_all = 0xFF
};
If you would now do this in your code (private):
if (flags & debuglvl_error) {
/* Do something when debuglvl_error flag is set */
}
There is no guarantee that debuglvl_error
will have the value 0x08
because it can be easily changed in the header file (of course its now questionable if you would to change these values but I'm just asking for nosiness). So.. is there way to make enum values private? Something like this:
public header file:
enum lvls {
debuglvl_debug,
debuglvl_info,
debuglvl_warning,
debuglvl_error,
debuglvl_all
};
private implementation:
enum lvls {
debuglvl_debug = 0x01
debuglvl_info = 0x02,
debuglvl_warning = 0x04,
debuglvl_error = 0x08,
debuglvl_all = 0xFF
};
My compiler does not let me do that, so is there another workaround for this? I guess its impossible to do so: do I need to rely on the fact that my header files are always unchanged?
What you are describing isn't possible for an enum
as it goes against what an enum
is. For what you want, you should just do variables with external linkage.
header file:
extern const int debug_debug, debug_info,...;
implementation file:
const int debug_debug = 0x01, debug_info = 0x02,...;
And for added security you can use the GCC's attribute syntax __attribute__((section("rodata")))
to place the variable in readonly memory.