Home > Mobile >  Declaration vs definition: is GCC wrong?
Declaration vs definition: is GCC wrong?

Time:05-19

According to ISO9899:2017 § 6.7-5:

A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that: — for an object, causes storage to be reserved for that object;

I guess it’s the exact same with all versions of the C standard.

When I try to compile the following code with GCC:

int main(void)
{   extern int myVariable; // Declaration of myVariable.
    int myVariable; // Definition of myVariable.
    int myVariable; // Definition of myVariable.
}

I get the following error:

error: redeclaration of 'myVariable' with no linkage

Unless I’m mistaken, the error isn't rather a redefinition?

CodePudding user response:

First you have this:

extern int myVariable; 

The extern keyword makes this a declaration for a variable with external linkage. Any such declaration will always refer to the same object.

Then you have:

int myVariable; 

This identifier has block scope (i.e. is defined inside of a function) and therefore has no linkage. Because it has no linkage, such a declaration is also a definition.

This is also an error (although you didn't show it) because you have conflicting declarations in the same scope for the same identifier, one with external linkage and one with no linkage.

Then in the same scope you have:

int myVariable; 

This is an error because you have two objects with the same name and no linkage in the same scope, and therefore multiple definitions.

Section 6.2.2p2 of the C standard describes linkages in more detail:

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

  •  Tags:  
  • c gcc
  • Related