C Programming - Declarations and Initializations - Discussion

Discussion Forum : Declarations and Initializations - Yes / No Questions (Q.No. 4)
4.
Is it true that a global variable may have several declarations, but only one definition?
Yes
No
Answer: Option
Explanation:

Yes, In all the global variable declarations, you need to use the keyword extern.

Discussion:
9 comments Page 1 of 1.

Venkat said:   7 years ago
#include<stdio.h>
int a;
int a;
int a;//several declarations;
main()
{
printf("%d\n",a);
}
output: 0.
---------------------------------------------------------------------------------------------
#include<stdio.h>
int a;
int a=2;
int a=3;//several definations
main()
{
printf("%d\n",a);

output:user@user:~/c$ cc t.c
t.c:4:5: error: redefinition of \'a\'
t.c:3:5: note: previous definition of \'a\' was here

---------------------------------------------------------------------------------------------
#include<stdio.h>
int a;
int a=2;//single defination
int a;
main()
{
printf("%d\n",a);
}
output: 2.
(1)

Harsha said:   1 decade ago
That means if we use an variable from other file which is globally defined once in that file. Every time when you are using that variable you have do declare that as extern. That means we can declare many times for ones defined global variable.

Karthik said:   9 months ago
If we declare a global variable without defining it will stored in bss (uninitialised data section) So, the memory is allocated when we access the data or assign a value to that variable.

Nilesh said:   1 decade ago
Once we declared variable globally then we can access it directly anywhere without declaring it again and again.

Divya said:   1 decade ago
Please elaborate with an example, how can a global variable have multiple declarations with one definition only?

Himanshu goel said:   1 decade ago
Please elaborate with an example. So that I can get it clearly.

Thanks in advance.

Akshay said:   1 decade ago
But there is no use of declaring it several times even if we can.

Bharath said:   9 years ago
It's not cleared. Please explain clearly.

Mani said:   3 years ago
Thanks for your explanation @Venkat.

Post your comments here:

Your comments will be displayed after verification.