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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With