When reading about functions in C++, I was taught that functions need declarations to be called. For example:
#include <iostream>
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
int sum(int x, int y) {
return x + y;
}
It returns an error, as there is no declaration for the function sum
.
main.cpp:4:36: error: use of undeclared identifier 'sum'
std::cout << "The result is " << sum(1, 2);
^
1 error generated.
To fix this, I'd add the declaration:
#include <iostream>
int sum(int x, int y); // declaration
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
int sum(int x, int y) {
return x + y;
}
My question is, why we don't add a declaration for the main
function, as we'd have to add for other functions, like sum
?
A definition of a function is also a declaration of a function.
The purpose of a declaring a function is to make it known to the compiler. Declaring a function without defining it allows a function to be used in places where it is inconvenient to define it. For example:
B.h
).In C++, a user program never calls main
, so it never needs a declaration before the definition. (Note that you could provide one if you wished. There is nothing special about a declaration of main
in this regard.) In C, a program can call main
. In that case, it does require that a declaration be visible before the call.
Note that main
does need to be known to the code that calls it. This is special code in what is typically called the C++ runtime startup code. The linker includes that code for you automatically when you are linking a C++ program with the appropriate linker options. Whatever language that code is written in, it has whatever declaration of main
it needs in order to call it properly.