Alex Rivera | Logout

Why main() in C++ cannot be inlined?

Asked 2011-08-08T10:56:52.413
70

I was reading the C++ FAQs and I noticed one sentence.

main() cannot be inline.

Why is this?

Edit
Report

3 Answers

14

Usually main() is called from systems init() function. Thus, it is needed that there can be exactly one definition for main().

Now, if we can inline the main() function and include in a header file then, for every translation unit there will be different definition for main(). Which is not allowed. You can declare main() in a namespace and inline it. But not the global main().

answered 2011-08-08T11:06:20.013
7

The C++ standard says that the main function cannot be inlined, per @Tomalak Geret'kal's reply. This response discusses possibility of inlining of the main function, were the restriction in the Standard removed.

Definition of Inline
The inline keyword is a suggestion to the compiler to paste the contents of the function in-situ. One intent is to remove the overhead present in calling and returning from a function (subroutine).

An important situation of inlining is the case where there is a pointer to the function. In this case, there must be at least one static copy of the function. In this case, the linker can resolve "external linkages" of the inlined function because there is one static version.

Important to note that the compiler and linker determine whether or not to paste the contents or calls a single instance of the function.

Also of note, functions that are not tagged by the programmer may also be inlined by the compiler.

Inlining the main function
Since there is only one invocation of main allowed, how it is linked is up to the compiler. Single instances of inline functions are allowed by the Standard. The compiler is allowed to convert an inlined function into a function call to a single instance. So the compiler would ignore an inline suggestion for the main function.

The compiler and linker would have to insure that only one instance of the inlined main function exists. This where the tricky part comes in, especially with external linkage. One process for ensuring one instance is to leave information that a translation has a 'main' function whether or not it is inlined. Note: When a call to an inline function is made, the compiler is allowed to remove the function from the symbol tables for extern

answered 2011-08-08T16:32:51.277
1

Since its the main() function, which starts the execution, when the code gets compiled to binary, everything is in the main() itself. so you can say, it already inlined!

And yes, its illegal to use inline for your C++ program, that's more about a syntax!

answered 2011-08-08T14:35:31.883

Your Answer