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

后端 未结 9 1767
小蘑菇
小蘑菇 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:03

    Is it a valid program?

    No.

    It is not a program as it has no executable parts.

    Is it valid to compile?

    Yes.

    Can it be used with a valid program?

    Yes.

    Not all compiled code is required to be executable to be valid. Examples are static and dynamic libraries.

    You have effectively built an object file. It is not a valid executable, however another program could link to the object main in the resultant file by loading it at runtime.

    Should this be an error?

    Traditionally, C++ allows the user to do things that may be seem like they have no valid use but that fit with the syntax of the language.

    I mean that sure, this could be reclassified as an error, but why? What purpose would that serve that the warning does not?

    So long as there is a theoretical possibility of this functionality being used in actual code, it is very unlikely that having a non-function object called main would result in an error according to the language.

提交回复
热议问题