Reputation: 9204
Extending from this question
I am having trouble to understand this code.
struct foo myfoo; // --> Is it forward declaration or object creation. ?
struct foo
{
int a;
};
int main()
{
return 0;
}
In the code marked arrow -->
Is it forward declaration or object creation. ?
If that is forward declaration then what is struct foo;
called ? If it's object creation or instantiation then how can it create object before struct definition.
On gcc
compiler its working fine but other compiler gives error.
gcc -Werror -Wall tst.c -o tst
Any suggestion or explanation about this behavior of gcc
? I could not have found anywhere it as documented.
Upvotes: 16
Views: 831
Reputation: 92854
Looks like tentative definition of myfoo
and because the definition of the struct is provided you get no error.
clang provides a comprehensive diagnostic when the type in not defined.
prasoon@ats-VPCEB3AGG:~$ cat tst.c
struct foo myfoo;
//struct foo{
// int x ;
//} ;
int main()
{
}
prasoon@ats-VPCEB3AGG:~$ clang tst.c
tst.c:1:12: error: tentative definition has type 'struct foo' that is never
completed
struct foo myfoo;
I don't think its a gcc bug, clang as well as comeau online is compiling the code.
$6.9.2/2
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.
Upvotes: 16
Reputation: 63190
struct foo myfoo;
That is a C variable definition of type foo
called myfoo
. C requires you to explicitly state the struct
in front of struct
variable declarations.
Now, your code shouldn't compile because the compiler has no idea at the place you defined your myfoo
, what type of foo
looks like. The compiler should complain about foo
being an incomplete type.
EDIT:
Scrap that, this would be called a tentative definition.
Upvotes: -2