redefinition of typedef

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.2/6 (Linkages of identifiers):

The following identifiers have no linkage: an identifier declared to be anything other than an object or a function [...]

and 6.7/3 (Declarations):

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;…


One piece of the idiom is missing. The forward declarations are independent from the definitions, so they should be in a separate header file.

// a_fwd.h

#ifndef A_FWD_H
#define A_FWD_H

typedef struct A_ A;

#endif

// a.h

#ifndef A_H
#define A_H

#include "a_fwd.h"

struct A_ {
};

#endif

Now it's always safe to include any headers in any order.


It is illegal to have two definitions of anything. A typedef is a definition, not just a declaration, so the one compiler was being quite lax to allow the redundancy.

Tags:

C

Gcc

Typedef