I accidentally made an error using the extern
keyword and then discovered that the compiler allowed my line of code. Why is the following program allowed? Does the compiler strip off the extern keyword? It does not even give a warning.
#include <iostream>
extern void test() { std::cout << "Hello world!" << std::endl; };
int main()
{
test();
}
This is not unusual, in fact, C++ internally does that exact same thing, note what 1.4/6 says:
The templates, classes, functions, and objects in the library have external linkage
The templates in the library very obviously have definitions, too. And why wouldn't they!
See what 3.1/2 and 3.4/2 (emphasis added) have to say:
A declaration is a definition unless it declares a function without specifying the function’s body (8.4), [or] it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a functionbody
[...]
When a name has external linkage , the entity it denotes can be referred to by names from scopes of other translation units or from other scopes of the same translation unit.
Your declaration has a function body, so it is a definition, and that's explicitly, perfectly allowable. The function has external linkage, which means you could refer to it by a name from a scope in another translation unit, but you're not required to do that.
You're still perfectly allowed to call it by its name in the current translation unit, and that is what you are doing.
Note that there's a clause about names at namespace scope, so your usage of the extern
keyword is somewhat redundant anyway.