I'm reading the Standard: N1570 and came across some misunderstanding. I wrote the following simple example:
test.h:
#ifndef TEST_H
#define TEST_H
extern int second;
#endif //TEST_H
test.c:
#include "test.h"
enum test_enum{
first,
second
};
But it fails to compile with the error:
error: ‘second’ redeclared as different kind of symbol
second
^~~~~~
This is strange, because Section 6.4.4.3#2 specifies:
2 An identifier declared as an enumeration constant has type int.
I our case the enumeration constant has file scope so I expected it to compile fine.
I rewrote the example above as follows:
main.c:
extern int second;
int main(int argc, char const *argv[])
{
printf("Second: %d\n", second);
}
And now linker complains:
undefined reference to `second'
Why? It should find the definition in the test.c because as the Section 6.2.2#5 specifies:
If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.
.pdfeach time (both are fine, just a suggestion) - David C. Rankintest.hwhich containsextern int second;When you declare anenum, the label (enum members) are also global constants -- the compiler sees two declarations ofsecond-- thus the redeclaration. - David C. Rankinintit works as expected. - St.Antarioenumto the header and includetest.hin main, or rename the variablesecondto something else intest.hand define it intest.c. - David C. Rankin