Xref: utzoo comp.lang.c:36589 comp.software-eng:4940 Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!samsung!spool.mu.edu!snorkelwacker.mit.edu!mit-eddie!uw-beaver!milton!blake.u.washington.edu!black From: black@blake.u.washington.edu (Jim Black) Newsgroups: comp.lang.c,comp.software-eng Subject: Re: Source File Organization Message-ID: <17268@milton.u.washington.edu> Date: 27 Feb 91 19:23:03 GMT References: <1991Feb26.045242.23453@rfengr.com> Sender: news@milton.u.washington.edu Organization: University of Washington, Seattle Lines: 66 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@blake.u.washington.edu)