Search code examples
cstaticextern

No error for extern variable redefined as static


I wrote the following code:

//f1.h
extern uint8 yyy;

//f1.c
#include "f1.h"
uint8 yyy;
...
//many more variables created by previous developers
static uint8 yyy; //created by previous developers
...

I assumed the previous developers had not named such a variable and created yyy. After some code review changes, I decided to rename yyy to something else and while searching f1.c for yyy, i found another static variable in f1.c as

static uint8 yyy;

Why didn the compiler warn me about another variable yyy initially?

While performing a Lint of the file, Lint just gives a warning:

Warning 401: symbol 'yyy' not previously declared static at line.

Assuming I had no Lint, is it OK to declare a static and a extern variable with the same name? What checks can I do to ensure that a variable name does'nt already exist while creating a new variable?


Solution

  • I believe the code you're describing (uint8 yyy; static uint8 yyy;) has undefined behavior. C99, 6.2.2 Linkages of identifiers:

    3. If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.

    5. [...] If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

    7. If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior is undefined.

    I.e. a compiler error is not required.