On Thu, Aug 11, 2005 at 11:27:27AM +0100, Stuart Bailey wrote:
Is there a good way around this problem or have I just got to bite the bullet and decide on one or other of the above and go with it?
I am really a C++ developer, but with some C experience.
Really, any coding style should make the code easier to read, and easier to maintain - this includes documentation.
I normally follow these rules for using globals and structures:
Only use globals if absolutely necessary (always try to pass data as arguments to functions, either as values or pointers)
Quite agree which is why I wasn't keen on the 'global' solution.
If a variable is required to remain in scope for multiple calls to a function, rather than make it global, make it static in the function that's using it.
Yes, if that's the intention then that's the way to do it.
Use structures to group related items together. So a structure containing say screen attributes would be OK, but just grouping variables together for the sake of it would not be acceptable.
Which is one of the reasons for not having a huge 'config' structure in my original question.
However none of this addresses my question really. The issue is trying to avoid repeating what is essentially the same thing over and over again when you have a large number of loosely associated values (the clock configuration parameters).
If they're globals you have to both initialise them and declare them as extern. Every global is (at least) duplicated as:-
int xsize = 1234; // in a .c file somewhere
and
extern int xsize; // in a .h file somewhere
If (as there should be) there are very few globals this is OK, but with the 50 or more the clock requires it's messy. They *are* required in different places because they're modified by the command line parsing and used in the X code which are separate source files.
If they were passed around as function parameters you'd end up with huge parameter lists to the functions, unless you move to the alternative struct .....
If you use a struct to contain the configuration you avoid many of the nasties of globals, however initialising the values is messy IMHO. You get stuff like:-
In a header file:-
struct ClockConfig { int xsize; int ysize; char bgcolor[COL_SIZE]; char fgcolor[COL_SIZE]; bool iconic; ... ... ... etc. };
and then, in the code somewhere:-
struct ClockConfig clockCfg = { 54, 54, "#123456", "#FFFFFF", FALSE, ... ... .. etc. };
Which, to my mind, is truly horrible and difficult to maintain because you have to be very careful to maintain the one-to-one correspondence between the initialisation values and the struct. Commenting will of course help but it again represents duplicated information which really shouldn't be necessary.