Search code examples
cstaticscopeextern

What's the use of static/extern in source files?


I have a very mixed notion of what happens when I compile many files - mostly when it comes to the visibility of things from one file to an other. From what I read, static limits the scope of a variable or function to the file itself. extern does the opposite. From that I would expect to be able and simply read a global extern from any file. That doesn't work in practice though as seen below.

main.c:

#include <stdio.h>

int main(void){
    printf("%d\n", b); // b is extern global
    return 0;
}

a.c:

static int a = 40;

b.c:

extern int b = 20;

I can't even compile:

> gcc main.c a.c b.c -o test
b.c:1:12: warning: ‘b’ initialized and declared ‘extern’ [enabled by default]
 extern int b = 20;
            ^
main.c: In function ‘main’:
main.c:4:20: error: ‘b’ undeclared (first use in this function)
     printf("%d\n", b); // b is extern global

Solution

  • You are doing all wrong.When we writing extern int b it means an integer type variable called b has been declared.And we can do this declaration as many times as needed. (remember that declaration can be done any number of times).By externing a variable we can use the variables anywhere in the program provided we know the declaration of them and the variable is defined somewhere.

    The correct way is

    main.c:

    #include <stdio.h>
    
    extern int b;   //declaration of b
     int main(void){
        printf("%d\n", b); // using b 
        return 0;
    }
    

    b.c:

    int b = 20;   //definition here
    

    and compile as gcc main.c b.c -o test

    I have omitted a.c as it was doing nothing in this example. To understand more about externs see this site.Its having very good content http://www.geeksforgeeks.org/understanding-extern-keyword-in-c/