Source File Organization
Jim Black
black at blake.u.washington.edu
Thu Feb 28 06:23:03 AEST 1991
Rick Farris writes :
>I have an enumerated type:
>
>typedef enum { A, B, C, D } CMD;
>
>and a corresponding array of ascii representations :
>
>char ltrs[] = { 'A', 'B', 'C', 'D' };
>
> [...]
>
>My problem is: How do I keep the darn things in sync?
>
>Suppose I add a new CMD, "Z", is there any way to ensure
>that ltrs[] is updated?
>
>The problem is exacerbated by the fact that the CMD enum,
>being a typedef, is in a header file that is included in
>many places. Since ltrs[] is an instantiated variable, it
>*can't* live in the same place. Where should it live?
>
One was is to use the C preprocessor, as follows:
1. Use a macro in an include file that groups all the related items together.
Eg, in "CmdStuff.h":
/* CMD ltr etc */
CmdStuff (A, 'A', ..)
CmdStuff (B, 'B', ..)
CmdStuff (C, 'C', ..)
CmdStuff (D, 'D', ..)
CmdStuff (Z, 'Z', ..)
2. Then in each source file (or header, as appropriate), define the CmdStuff
macro to do what you want in the particular case, and #include "CmdStuff.h"
locally.
The CMD enum definition would look like this:
#define CmdStuff(enumval, ltr, ..) enumval,
typedef enum {
#include "CmdStuff.h" /* enum values get enumerated here */
} CMD;
#undef CmdStuff
And the ltrs[] definition would look like this:
#define CmdStuff(enumval, ltr, ..) ltr,
char ltrs[] = {
#include "CmdStuff.h" /* corresponding letter codes get enumerated here */
};
#undef CmdStuff
That's the basic idea, you can do more with this than these examples show.
Everything is declared together in one place ("CmdStuff.h", here):
each time you add a CmdStuff() entry you will be forced to declare
all appropriate parallel values, as intended.
P.S. I can't remember if some C compilers might complain about a trailing
comma in the aggregate initialization (mine doesn't) - but you can add a
trailing null/nil/bottom entry in such cases. Often that's useful anyway.
--
Jim Black (black at blake.u.washington.edu)
More information about the Comp.lang.c
mailing list