I am possibly doing this incorrectly and this is much a question about why it works in one compiler and not the other.
I have a large C application, and I am trying to follow the style of not including header files from within other header files. Instead, using forward declarations; thus I am trying the following.
// in A.h
typedef struct A_ A;
typedef struct B_ B;
struct A_ {
double a;
B *b;
};
// in B.h
typedef struct B_ B;
struct B_ {
int c;
};
// in C.h
typedef struct A_ A;
typedef struct B_ B;
void function_do_something(A*, B*);
// in C.c
#include "A.h"
#include "B.h"
#include "C.h"
void function_do_something(A* a, B* b) {
...
}
This paradigm compiles and runs in Ubuntu 11.10 gcc -- but it gives compiler erros in OpenSUSE gcc that say "redefinition of typedef".
I have been doing my development in Ubunutu and so hadn't realised that this paradigm might be incorrect. Is it just that this is plain wrong and Ubuntu's gcc is being too nice?
I was surprised by this because I'm fairly sure that redeclaring the same typedef in the same scope is legal in C++, but apparently it is not legal in C prior to the 2011 standard.
First, typedef names have no linkage:
ISO/IEC 9899:1999 + TC3 6.2.6/6:
The following identifiers have no linkage: an identifier declared to be anything other than an object or a function [...]
and 6.7/3:
If an identifier has no linkage, there shall be no more than one declaration of the identifier (in a declarator or type specifier) with the same scope and in the same name space, except for tags as specified in 6.7.2.3.
So you need to ensure that each typedef declaration appears only once at file scope in each translation unit.
The 2011 C standard allows redeclaration of typedef names. 6.7 3 says:
… a typedef name may be redefined to denote the same type as it currently does, provided that type is not a variably modified type;…