Hello everyone, I'm trying to split the C source code of one file into nearly 10 different. It does not work properly due to global variables declared in one header file but used in more than one C files. Compiling of such a project works fine but the linking errors L104 and L118 occur. My question: How can I prevent this errors without creating one header file for every C file? My idea is the following, but it is complicated and additionally unsure if it works:
#ifdef CPVAR extern unsigned char global_var1; extern unsigned int global_var2; extern unsigned long global_var3; #elseif unsigned char global_var1; unsigned int global_var2; unsigned long global_var3; #define CPVAR #endif
Tobias, In short, yes... when you use "extern" that's considered a declaration. While many will decry what you're trying to do with global variables to be heresy, there is a fairly easy way to do it. Make a file called something obvious like GLOBALS.H so that everyone who has to maintain this code will know of your treason. In it, do something like this:
#ifdef DEFINEGLOBALSHERE #define GLOBAL #else #define GLOBAL extern #endif GLOBAL unsigned char global_var1; GLOBAL unsigned int global_var2; GLOBAL unsigned long global_var3;
#define DEFINEGLOBALSHERE
"Note that this only works with plain vanilla definitions. Initializations won't work. Using the _at_ keyword won't work." It is left as an exercise for the student to devise a scheme that would support initialisers and the _at_ keyword...
yes... we can only post so much in the way of preprocessor kung-fu in any one thread. :)