function main without definition in C and C++

c, c++

Solution

Why this code compile successful in C and will give you an error in C++?

Because of C++ name mangling. Basically, in all practical implementations, the linker looks for a symbol named `main` (or variants of it, I've seen `_main` on Apple's platforms) - in C, that can be either the `main()` function or an extern storage variable named `main` - the point is that usually C implementations (compilers, toolchains) don't differentiate between variables and functions at the linker level, that's why providing one symbol, be it either a variable or a function, named `main()` may seem to be enough. In fact, in a hosted environment, as per the Standard, the resulting program (executable) won't be conforming, because there, it is required that the `main()` function be implemented.

In C++, usually name mangling is used (in order to achieve features of C++ such as function overloading), and that means that the compiler names the resulting symbol in the executable file differently depending on its type, on the fact if it's a function, a variable, a function with a different signature, and other circumstances. So the linker basically won't find the symbol corresponding to the expected `int main(int, char *[])` function and will issue an error message.

Is it standard-conforming?

Not defining the `main()` function isn't (see the first part). As far as I can tell, having a variable named `main` along with the main function is valid C++, but it is certainly bad practice.

Can you quote the Standard?

Yes please (emphasis mine):

C++ 98, paragraph 3.6.1:

A program shall contain a global function called `main()`, which is the designated start of the program. It is implementation-defined whether a program in a freestanding environment is required to define a `main()` function.

C99, paragraph 5.1.2.2.1

5.1.2.2.1 Program startup

1 The function called at program startup is named main. The implementation declares no prototype for this function. I

Problem

Why this code compile successful in C and will give you an error in C++? ``` int main; ``` Is it standard-conforming in a hosted environment? Can you quote the standard? I've tested it with gcc.

Original source