Extern in C

Written on: October 10, 2015

The extern keyword does not allocate memory for that variable. It will only declare a variable/function and tell the compiler that this variable will be defined elsewhere (it “extends” the visibility). By default, all functions are prepended with the ‘extern’ keyword to the beginning of them when you declare them, ie in a header file. extern is also added to the definitions of the function (when you write the body of the code in a .c file). This keyword tells the compiler to allow any files linked to this function’s file to use the functions themselves.

All of this happens automatically so extern on functions aren’t the most interesting part. Variables are where things get a little more complicated.

When you declare:

extern int i;

This will declare variable ‘i’ but will not define it (no memory will be allocated). You can do this as many times as you want and memory will never be allocated. But this also means that you can’t define it in this file either.

If you do:

extern int i;
    int main(void) {
    i = 5;
    return 0;
}

This won't compile and the compiler will tell you that 'i' was never defined. The extern keyword specifically tells the compiler that the variable will be defined elsewhere. Now if you were to include let's say some header file that had:

int i = 10;

Then you would be able to use 'i' in your other file.

#include "someheader.h"
    extern int i;
    int main(void) {
    i = 5;
    return 0;
}

The only case where you can declare a variable as extern and use it is if you also initialize it on the same line.

extern int i = 10;