Search code examples
cc89

Variable declaration and definition mismatch


I am using a C89 compiler (embedded systems).

I ran into some C code where one translation unit defines a variable as bool varName;, where bool is a typedef of unsigned char. Another translation unit forward declares the variable as follows: extern char varName;.

This is obviously a type mismatch, and is an error. My question is, what exact rule does this violate? My knee-jerk reaction was that it is an ODR violation, but there is a single definition so I'm not confident that this is an ODR violation.


Solution

  • 6.2.7p2

    All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined.

    The C89 standard has the same paragraph.

    Declarations referfing to the same object is further explained in the paragraph on linkage:

    An identifier declared in different scopes or in the same scope more than once can be made to refer to the same object or function by a process called linkage . There are three kinds of linkage: external, internal, and none.

    In the set of translation units and libraries that constitutes an entire program, each instance of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each instance of an identifier with internal linkage denotes the same object or function. Identifiers with no linkage denote unique entities.

    Compatible types essentially means identical types, with some minor caveats (e.g., extern int foo[]; is compatible with extern int foo[3];).