I came across some code today that surprised me. A variable was defined (outside of a function) in the .c file as being static. However, in the .h file it was declared as being extern. Here is a similar example of the code:
Structure definitions and declaration in .h:
typedef struct
{
unsigned char counter;
unsigned char some_num;
} One_Struct;
typedef struct
{
unsigned char counter;
unsigned char some_num;
const unsigned char * p_something;
} Another_Struct;
typedef struct
{
One_Struct * const p_one_struct;
Another_Struct * const p_another_struct;
} One_Useful_Struct;
extern One_Useful_Struct * const p_my_useful_struct[];
Definition and initialization in .c:
static One_Useful_Struct * const p_my_useful_struct[MAX_USEFUL_STRUCTS] =
{
&p_my_useful_struct_regarding_x,
&p_my_useful_struct_regarding_y,
};
Question: So my question is, why didn't I receive a compiler error or warning?
The code has been successfully running in other projects for some time now. I did note that the pointer is never used outside of the .c file in which it is defined and was properly defined as static (I removed the external declaration). The only reason that I found it was because I ran Lint on the project and Lint picked it up.
It's certianly not standard C. GCC and clang both detect and give an error on this case:
$ gcc example.c
example.c:4: error: static declaration of ‘x’ follows non-static declaration
example.c:3: error: previous declaration of ‘x’ was here
$ clang example.c
example.c:4:12: error: static declaration of 'x' follows non-static declaration
static int x;
^
example.c:3:12: note: previous definition is here
extern int x;
^
1 error generated.
You must be using a pretty permissive compiler - maybe Visual Studio? I just checked on my Windows machine and VS2003 accepts my example program silently. Adding /Wall
does give a warning:
> cl /nologo /Wall example.c
example.c
example.c(4) : warning C4211: nonstandard extension used : redefined extern to static
Looks to me like you're using an extension of whatever compiler it is that you're using.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With