Does int main() need a declaration on C++?

C++MainForward DeclarationFunction Declaration

C++ Problem Overview


I was taught that functions need declarations to be called. To illustrate, the following example would give me an error as there is no declaration for the function sum:

#include <iostream>

int main() {
  std::cout << "The result is " << sum(1, 2);
  return 0;
}

int sum(int x, int y) {
  return x + y;
}

// 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;
}

Why the main function doesn't need the declaration, as other functions like sum need?

C++ Solutions


Solution 1 - C++

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:

  • If a function is used in a source file (A) other than the one it is defined in (B), we need to declare it in A (usually via a header that A includes, such as B.h).
  • If two or more functions may call each other, then we cannot define all those functions before the others—one of them has to be first. So declarations can be provided first, with definitions coming afterward.
  • Many people prefer to put “higher level” routines earlier in a source file and subroutines later. Since those “higher level” routines call various subroutines, the subroutines must be declared earlier.

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.

Solution 2 - C++

> I was taught that functions need declarations to be called.

Indeed. A function must be declared before it can be called.

> why we don't add a declaration for the main function?

Well, you didn't call main function. In fact, you must not call main at all1, so there is never a need to declare main before anything.

Technically though, all definitions are also declarations, so your definition of main also declares main.


Footnote 1: The C++ standard says it's undefined behaviour to call main from within the program.

This allows C++ implementations to put special run-once startup code at the top of main, if they aren't able to have it run earlier from hooks in the startup code that normally calls main. Some real implementations do in fact do this, e.g. calling a fast-math function that sets some FPU flags like denormals-are-zero.

On a hypothetical implementation, calling main could result in fun things like re-running constructors for all static variables, re-initializing the data structures used by new/delete to keep track of allocations, or other total breakage of your program. Or it might not cause any problem at all. Undefined behaviour doesn't mean it has to fail on every implementation.

Solution 3 - C++

The prototype is required if you want to call the function, but it's not yet available, like sum in your case.

You must not call main yourself, so there is no need to have a prototype. It's even a bad a idea to write a prototype.

Solution 4 - C++

No, the compiler does not need a forward declaration for main().

main() is a special function in C++.

Some important things to remember about main() are:

  1. The linker requires that one and only one main() function exist when creating an executable program.
  2. The compiler expects a main() function in one of the following two forms:
int main () { /* body */ } 
int main (int argc, char *argv[]) { /* body */ } 

where body is zero or more statements

An additional acceptable form is implementation specific and provides a list of the environment variables at the time the function is called:

int main (int argc, char* argv[], char *envp[]) { /* body */ }

The coder must provide the 'definition' of main using one of these acceptable forms, but the coder does not need to provide a declaration. The coded definiton is accepted by the compiler as the declaration of main().

  1. If no return statement is provided, the compiler will provide a return 0; as the last statement in the function body.

As an aside, there is sometimes confusion about whether a C++ program can make a call to main(). This is not recommended. The C++17 draft states that main() "shall not be used within a program." In other words, cannot be called from within a program. See e.g. Working Draft Standard for C++ Programming Language, dated "2017-03-21", Paragraph 6.6.1.3, page 66. I realize that some compilers support this (including mine), but the next version of the compiler could modify or remove that behavior as the standard uses the term "shall not".

Solution 5 - C++

It is illegal to call main from inside your program. That means the only thing that is going to call it is the runtime and the compiler/linker can handle setting that up.This means you do not need a prototype for main.

Solution 6 - C++

A definition of a function also implicitly declares it. If you need to reference a function before it is defined you need to declare it before you use it.

So writing the following is also valid:

int sum(int x, int y) {
  return x + y;
}

int main() {
  std::cout << "The result is " << sum(1, 2);
  return 0;
}

If you use a declaration in one file to make a function known to the compiler before it is defined, then its definition has to be known at linking time:

main.cpp

int sum(int x, int y);

int main() {
  std::cout << "The result is " << sum(1, 2);
  return 0;
}

sum.cpp

int sum(int x, int y) {
  return x + y;
}

Or sum could have its origin in a library, so you do not even compile it yourself.

The main function is not used/referenced in your code anywhere, so there is no need to add the declaration of main anywhere.

Before and after your main function the c++ library might execute some init and cleanup steps, and will call your main function. If that part of the library would be represented as c++ code then it would contain a declaration of int main() so that that it could be compiled. That code could look like this:

int main();

int __main() {
  __startup_runtime();

  main();
 
  __cleanup_runtime();
}

But then you again have the same problem with __main so at some point there is no c++ anymore and a certain function (main) just represents the entry point of your code.

Solution 7 - C++

Nope. You can't call it anyway.

You only need forward declarations for functions called before they are defined. You need external declarations (which look exactly like forward declarations on purpose) for functions defined in other files.

But you can't call main in C++ so you don't need one. This is because the C++ compiler is allowed to modify main to do global initialization.

[I looked at crt0.c and it does have a declaration for main but that's neither here nor there].

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVinicius BrasilView Question on Stackoverflow
Solution 1 - C++Eric PostpischilView Answer on Stackoverflow
Solution 2 - C++eerorikaView Answer on Stackoverflow
Solution 3 - C++Matthieu BrucherView Answer on Stackoverflow
Solution 4 - C++GardenerView Answer on Stackoverflow
Solution 5 - C++NathanOliverView Answer on Stackoverflow
Solution 6 - C++t.nieseView Answer on Stackoverflow
Solution 7 - C++JoshuaView Answer on Stackoverflow