I have an include file with 100+ global variables. It’s being used in a library, but some programs that I’m linking the lib to also need to access the globals.
The way it was built:
// In one library .c file
#define Extern
// In the programs that use the globals
#define Extern extern
// In the .h file
Extern int a,b,c;
I had a hard time understanding why the original programmer did that so I removed that define Extern stuff. Now I think I understand the thing about TU with the help of stackoverflow:
1,
2,
3.
Now I understand that I should define the global variables in one .c file in the library and use extern in the .h file. The problem is that I don’t want to duplicate code.
Should I go back to that #define Extern voodoo?
The trick here is that the .h file is being used in two different ways – it’s being used as a normal .h file where all the globals are declared
externand it’s also being used to define the globals themselves (with noextern). This is an ugly hack but you can understand why someone felt it necessary if you have a large number of globals (a sure sign of very bad software design !).Anyway, there is a somewhat more elegant solution – you can put all your globals in a single global struct, e.g.
–
–
Then when you need to refer to a global it’s e.g.
globals.ainstead of justa, which might seem like an inconvenience but this is arguably clearer and more manageable than just having naked globals scattered throughout the code.