Is ‘int main;’ a valid C/C++ program?

后端 未结 9 1764
小蘑菇
小蘑菇 2020-12-23 15:32

I ask because my compiler seems to think so, even though I don’t.

echo \'int main;\' | cc -x c - -Wall
echo \'int main;\' | c++ -x c++ - -Wall

9条回答
  •  星月不相逢
    2020-12-23 16:08

    My point, I suppose, is that I really think this should be an error in a hosted environment, eh?

    The error is yours. You didn't specify a function named main that returns an int and tried to use your program in a hosted environment.

    Suppose you have a compilation unit that defines a global variable named main. This might well be legal in a freestanding environment because what constitutes a program is left up to the implementation in freestanding environments.

    Suppose you have another compilation unit that defines a global function named main that returns an int and takes no arguments. This is exactly what a program in a hosted environment needs.

    Everything's fine if you only use the first compilation unit in a freestanding environment and only use the second in a hosted environment. What if you use both in one program? In C++, you've violated the one definition rule. That is undefined behavior. In C, you've violated the rule that dictates that all references to a single symbol must be consistent; if they aren't it's undefined behavior. Undefined behavior is a "get out of jail, free!" card to developers of an implementation. Anything an implementation does in response to undefined behavior is compliant with the standard. The implementation doesn't have to warn about, let alone detect, undefined behavior.

    What if you use only one of those compilation units, but you use the wrong one (which is what you did)? In C, the situation is clear-cut. Failure to define the function main in one of the two standard forms in a hosted environment is undefined behavior. Suppose you didn't define main at all. The compiler/linker doesn't haven't to say a thing about this error. That they do complain is a nicety on their behalf. That the C program compiled and linked without error is your fault, not the compiler's.

    It's a bit less clear in C++ because failure to define the function main in a hosted environment is an error rather than undefined behavior (in other words, it must be diagnosed). However, the one definition rule in C++ means linkers can be rather dumb. The linker's job is resolving external references, and thanks to the one definition rule, the linker doesn't have to know what those symbols mean. You provided a symbol named main, the linker is expecting to see a symbol named main, so all is good as far as the linker is concerned.

提交回复
热议问题