Declaration and definition in C programming with extern

152 views Asked by At

This may seem simple to one's eye but, this question is itching me in many ways.

  1. my question is about declaration and defenition on variables in c.

there are actually many explanation in internet regarding this one and there is not just one solution to this issue as many view points are placed in this issue. i want to know the clear existance of this issue.

int a;

just take this is this a declaration or definition?, this one when i use printf, it has 0 as value and address as 2335860. but if this declaration then how come memory is allocated for this.

int a;
int a;

when i do this it says previous declaration of 'a' was here and redeclaration of 'a' with no linkage.

  1. some sources say redeclaration is permitted in c and some say dont what is the truth?

2

There are 2 answers

6
Mohit Jain On

int a; just take this is this a declaration or definition?

int a; if written in global scope is a tentative definition. Which means if no other definitions are available in current compilation unit, treat this as definition or else this is a declaration.

From 6.9.2 External object definitions in C11 specs:

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.

int i4; // tentative definition, external linkage
static int i5; // tentative definition, internal linkage

So you are effectively doing multiple declarations but getting the address and value because of tentative definition rule.

some sources say redeclaration is permitted in c and some say dont what is the truth?

Redeclaration is permitted in C. But redefinition is not.

Related question: What is the difference between a definition and a declaration?

there are actually many explanation in internet

Prefer a good book instead of internet to get the hold of language. You can choose a good book from: The Definitive C Book Guide and List

2
haccks On

int a is a definition and can be used in place of declaration. A variable can have many declarations but must have only one definition. In case of

int a;
int a;  

there are two definition of a in the same scope. Providing linkage to one of them will make your compiler happy

int a;
extern int a;