Skip to content
Theory · Functions · lesson 1 of 11

Declaration and definition

The compiler reads a file from top to bottom. When it reaches a function call, it must already know the function's name, parameter types and return type. That is why a function defined below main cannot be called from main:

C++
#include <iostream>

int main() {
    std::cout << twice(21) << '\n';  // ✗
}

int twice(int x) {
    return x * 2;
}
TEXT
error: use of undeclared identifier 'twice'

Moving twice above main makes the error go away. But if the function is defined in another file, there is nothing to move—the compiler must learn about it another way.

Declaration

A declaration tells the compiler a function's name, its parameter types and its return type. A declaration has no body—a semicolon takes its place. Such a declaration is also called a prototype.

C++
int twice(int x);

Parameter names in a declaration may be left out: int twice(int); means the same thing. The compiler needs only the types, while the name x tells the reader what goes into the function.

A definition is a declaration together with a body in curly braces, so a function defined above main needs no separate declaration. A function may be declared several times but defined only once.

Calling before the definition

A declaration above main solves the problem: the call compiles, and the body can stay at the end of the file.

C++
#include <iostream>

int twice(int x);

int main() {
    std::cout << twice(21) << '\n';  // 42
}

int twice(int x) {
    return x * 2;
}

To check the call twice(21), the compiler needs only the declaration: the function takes an int and returns an int. If the body is in another .cpp file, the linker connects the call to it. Header files rely on this: they hold declarations, while definitions go in .cpp files. #include <iostream> works the same way: it inserts declarations from the standard library into the file.

Common mistake

The function is declared, but its definition is forgotten. The compiler sees no error, and the build stops at the next step:

C++
int twice(int x);

int main() {
    return twice(21);  // ✗
}
TEXT
undefined reference to `twice(int)'

The linker reports this, not the compiler. The declaration was enough to check the call, but no file of the program holds the body of twice. In the course exercises, the same message reads differently: undefined symbol: twice(int).

The same error appears when the definition's parameter types do not match the declaration. int twice(long x) is a different function, and the declared twice(int) is again left without a body.