Why doesn't this compile? The linker can't find main, but why is this the case?
namespace somenamespace{
int main(void){
return 0;
}
}
Why doesn't this compile? The linker can't find main, but why is this the case?
namespace somenamespace{
int main(void){
return 0;
}
}
3.6.1/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. [ Note: in a freestanding environment, start-up and termination is implementation-defined; startup contains the execution of constructors for objects of namespace scope with static storage duration; termination contains the execution of destructors for objects with static storage duration. —end note ]
Your example has 'main' (intended as the program entry point) as a namespace function and hence your code is ill-formed. This does not mean that a function 'main' can not be defined as you did. It just means that a global namespace scope definition of 'main' in accordance with the Standard defined signature is required for a free standing program. hosted program
The linker is required to arrange for the program's execution to start in a global function called "main". The whole point of benig able to create your own namespaces - as you've done - is to avoid putting things in the global namespace so they won't be accidentally picked up by other code or the linker. You're explicitly saying "I'm calling this function main, but that's only meaningful within the context of somenamespace
- if you don't know about somenamespace you won't find or be able to use it".
Implementation wise, the mangled name of your main symbol has been changed from the expected name due to the namespace, so the linker just doesn't find the symbol table entry it needs.
The linker is looking for ::main
, not ::somenamespace::main
. The main
that is called at program startup must be in the global namespace.
@Chubsdad has pointed you at the relevant language in the standard that states this. But the standard is now written in a bizarre 'standardese' that bears a lot of resemblance to legalese. I felt a plain english statement of what was going on might be better.
Note: There is a reason the standard is written this way. In the standard you want every term you use to have a very precise and well-defined meaning, and you do not want that meaning to vary depending on context because it makes the standard much harder to interpret. This is actually very similar to the reason that legalese looks the way it does.