user1386966
user1386966

Reputation: 3392

how to use extern in C?

I have this code:

#include <stdio.h>

extern int x;
void a() {
    int x = 100;
    printf("%d ",x );
    x += 5;
}

void b() {
    static int x = -10;
    printf("%d ", x);
    x += 5;
}

void c(){
    printf("%d ", x);
    x += 2;
}

int main() {
    int x = 10;
    a();
    b();
    c();
    a();
    b();
    c();
    printf("%d ", x);
    getchar();
    return 0;
}

int x = 0;

I was sure that the fact that extern in declared here, I will have a compilation error - but everything passed. also , what is the meaning of extern when it's inside the C file itself? shouldn't it be in another file? Is there a way to declare this variable in order for this not to compile?

Upvotes: 1

Views: 2163

Answers (3)

askmish
askmish

Reputation: 6674

You have a declaration for an identifier at file scope, so if no other declaration for the identifier would've been existing at file scope, the identifier would have had and external linkage. But, you've defined the identifier at file scope at the last line, in the pasted code.

So,extern int x;

refers to the globally defined: int x = 0; at the bottom of your file. :)

If you run this code you should get x's value as 2 and subsequently 4 because the externed x variable refers to the int x=0 after the main().

Upvotes: 1

Ren&#233; Kolař&#237;k
Ren&#233; Kolař&#237;k

Reputation: 1286

Extern is used for declaration a variable in a compilation unit, this variable was defined in other compilation unit.

What is the difference between a definition and a declaration?

For functions it is optional.

Read: http://en.wikipedia.org/wiki/External_variable

In your piece of code, each of the three function uses another 'i'. Only c() uses the global x.

Upvotes: 0

hmjd
hmjd

Reputation: 121961

The extern keyword declares a variable, and tells the compiler there is a definition for it elsewhere. In the case of the posted code, the definition of x occurs after main(). If you remove the int x = 0; after main() the code will not build (it will compile but will fail to link due to undefined symbol x).

extern is commonly used to declare variables (or functions) in header files and have the definition in a separate source (.c) file to make the same variable available to multiple translation units (and avoid multiple definition errors):

/* my.h */
#ifndef MY_HEADER
#define MY_HEADER
extern int x;
#endif

/* my.c */
#include "my.h"
int x = 0;

Note that the declaration of x in functions a(), b() and main() hide the global variable x.

Upvotes: 2

Related Questions