Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

duplicate external static declarations not allowed in visual studio?

I was studyng the concept of declaration and definitions (linkage, scope, duration).

But I found one unexplainable error:

The following code is fine in both gcc and visual studio 2010

#include <stdio.h>

extern int a = 7;
extern int a;

int main()
{
    printf("%d\n", a);
}

But the following code generates an error in visual studio but is fine in gcc:

#include <stdio.h>

static int a = 7;
static int a;

int main()
{
    printf("%d\n", a);
}

error C2370: 'a' : redefinition; different storage class

Is it just a bug in visual studio compiler?

EDIT: this question turned out to be a duplicate of this.

like image 337
SHH Avatar asked Feb 15 '26 21:02

SHH


1 Answers

static int a; by itself without an initializer is a "tentative definition", so it should be fine. It looks like Microsoft has some kind of extension that's catching you.

Edit - it does look like a Microsoft problem. Check out this related question. The C spec itself is pretty clear that your code is fine. From 6.9.2 External object definitions:

A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.

like image 168
Carl Norum Avatar answered Feb 17 '26 11:02

Carl Norum