Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between int and extern int in C?

Tags:

c

int i;        // A.
extern int i; // B.

I know A is a variable's definition. Namely, the compiler creates an object and assigns a block of memory to the variable i. But what is B? What's the difference between the definition and the declaration?

like image 534
runeveryday Avatar asked Dec 01 '25 08:12

runeveryday


2 Answers

It's a declaration. It says there is an integer i that will be defined elsewhere.

like image 75
Matthew Flaschen Avatar answered Dec 03 '25 22:12

Matthew Flaschen


Case A) is a 'tentative defintion' with external linkage. You can have multiple of these in a single translation unit, and all will refer to the same variable. The definition is called tentative because it will only zero-initialize the variable if there is no other definition with explicit initializer in the translation unit.

Case B) is a declaration but not a definition (tentative or otherwise), because there is no initializer present and no storage will be reserved. There must be a valid definition of the variable elsewhere in this or another translation unit. If there's a previous declaration of the variable with internal linkage in scope, the variable will have internal linkage, otherwise external, ie

static int foo;
extern int foo;

results in a valid tentative definition with internal linkage, whereas

extern int foo;
static int foo;    

is invalid as you have a declaration with external linkage followed by a (tentative) definition with internal linkage.

See C99 sections 6.2.2 and 6.9.2 for details.

like image 33
Christoph Avatar answered Dec 03 '25 21:12

Christoph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!