Is it possible in C to have mutually referencing static variable initializers, as shown in the example below?
The example compiles, without warning in gcc -Wall, if line 2 is added to pre-declare “B”. Line 2 is distasteful because it also defines B, as does line 4. The splint lint program, with -weak checking, warns that “B” is defined twice: “Variable B redefined. A function or variable is redefined. One of the declarations should use extern.”
Typically a declaration would be made with the extern keyword, but extern and static cannot be used together, and will not compile under gcc.
#include <stdio.h> /*1*/
volatile static void * B; /*2*/
volatile static void * A = &B; /*3*/
volatile static void * B = &A; /*4*/
int main() /*5*/
{ /*6*/
printf("A = %x, B = %x\n", (int)A, (int)B); /*7*/
return 0; /*8*/
} /*9*/
Thank you
Notwithstanding the strange placement of
volatilewith relation tostatic, the code you posted is perfectly valid C. It uses a C-specific feature called tentative definitions. This feature makes sure that you have only oneBin your program: both definitions ofBdefine the same entity. There’s nothing “distasteful” about it.The warning you get from splint is invalid. In C++ language this would indeed constitute a multiple-definition error, but not in C. The comment about
externmakes no sense whatsoever within the context of C language.