Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

duplicate declaration global variable in C [duplicate]

why does this work within global scope:

static int a;
static int a=0;

but not within function's body:

void foo()
{
    static int b;
    static int b=0; //error: Duplicate declaration of global variable 'b'
    ...

using clion 2017.3.1, C99, gcc5.4

like image 913
John Avatar asked Jan 15 '18 18:01

John


1 Answers

The first one, in global scope, is an example for a so called Tentative definition.

A tentative definition is an external declaration without an initializer, and either without a storage-class specifier or with the specifier static.

A tentative definition is a declaration that may or may not act as a definition. If an actual external definition is found earlier or later in the same translation unit, then the tentative definition just acts as a declaration.

In the second example, b has block scope and no linkage, in other words: the declarations are not external. Hence, the tentative definition rule does not apply.

like image 127
sergej Avatar answered Oct 10 '22 23:10

sergej