Course contentsShow
← C
Lesson 922 of 1,21913. Advanced CFree lesson

Using `extern` with functions

Using extern with functions

What you'll learn: How to tell the C compiler that a function's definition exists in a different file so you can call it from your current code.

The "Office Assistant" Analogy

Imagine you are writing a manual for a new office assistant. In your instructions, you tell them: "When the phone rings, ask the Accounting Department to process the invoice."

If the assistant looks around your room and doesn't see an "Accounting Department," they might get confused and stop working. To fix this, you add a note at the top of your manual: "Note: The Accounting Department exists; they are just in the building next door." This prevents the assistant from panicking.

In C, the extern keyword acts as that note. It tells the compiler, "I’m going to call this function now. You won't find the code for it in this file, but trust me, it exists somewhere else in the project."

Why Use extern?

By default, functions in C have "external linkage." This means they are visible to the entire program. However, if you want to use function A (defined in file_1.c) inside file_2.c, file_2.c needs a declaration so it knows the function's name, return type, and parameters.

While many programmers simply use header files (.h) to handle this, understanding the extern keyword is vital for grasping how the linker connects different pieces of your program.

Seeing it in Action

Suppose you have two files. One contains the logic, and the other is your main entry point.

file_logic.c (The Definition)

#include <stdio.h>

void celebrate_success(int count) {
    printf("Success! You've completed %d tasks.\n", count);
}

main.c (The Usage)

#include <stdio.h>

// We tell the compiler the function exists elsewhere
extern void celebrate_success(int count);

int main() {
    // Now we can call it without a compiler error
    celebrate_success(5);
    return 0;
}

When you compile these files together, the compiler sees the extern declaration in main.c and leaves a "placeholder." During the final stage (linking), the computer finds the actual code in file_logic.c and plugs it in.

Technical Nuance

Interestingly, for functions, the extern keyword is actually optional in declarations. Simply writing void celebrate_success(int count); (a function prototype) acts as an implicit extern. However, using the keyword explicitly makes your intentions clear to other developers: this function is a guest from another file.

Key takeaway

The extern keyword declares a function without defining it, allowing you to call functions across different files by promising the compiler that the definition will be found during the linking phase.