Sun Mon Tue Wed Thu Fri Sat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
extern int counter; int counter = 0;I am big fan of encapsulation and I like clean include files that hide implementation details that are not necessary for the users of the functions given in the header file. The implementation for a certain header file depended on a global counter that I did not want to include in the header file itself, but it needed to be incremented somewhere else and initialized to zero. So, I wrote in that other location, the main file (containing the main function):
extern int counter = 0;And this resulted in a compile error, because you are not allowed to initialize a variable that is declared extern. Next, I changed the line into:
int counter = 0;Now, I got a linking error saying that the other external definition (in the C file implementing the header file that relied on the counter variable) was not defined anywhere. This is because although it is defined in the main file, it was not defined as extern and thus not visible on the outside and thus becoming invisible for the linker that combines all the separately compiled C programs into one executable. It dawned on me that if I would have placed the extern declaration in the header file, it would have worked because then during the compilation of both C programs it would have been defined as extern and in the main program I still would have been able to initialize it. Although it is not common to see a 'double' declaration in a C file, like the above, and even looks a bit confusing, it is actually somthing that is done all the time, because the C preprocessor put both declarations into the intermediate file that is compiled by the actual compiler.
In this picture there are: a small puprple cauliflower, a romanesco broccoli, a fennel, two red cabbages, a green and a orange pumpkin, and a leaf of curly kale.