Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type of declaration is this?

Tags:

c

gcc

struct

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.

like image 670
Omkant Avatar asked Nov 29 '12 14:11

Omkant


1 Answers

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.


like image 115
Prasoon Saurav Avatar answered Oct 03 '22 17:10

Prasoon Saurav