Sobes.tech
Junior — Middle

Can you explain what the extern keyword does in C/C++ programming language?

sobes.tech AI

Answer from AI

The keyword extern in C/C++ is used to declare a variable or function that is defined elsewhere (usually in another file). This allows the same variable or function to be used across multiple files, avoiding duplication and conflicts.

For example, if a global variable is defined in one file:

// file1.c
int count = 0;

Then in another file, it can be declared using extern:

// file2.c
extern int count;

void increment() {
    count++;
}

Thus, extern tells the compiler that the definition of the variable or function is outside the current file, and linking will occur at the linking stage.