How can a program with a global variable called main instead of a main function work?

前端 未结 7 1477
长情又很酷
长情又很酷 2020-12-07 12:05

Consider following program:

#include 
int main = ( std::cout << \"C++ is excellent!\\n\", 195 ); 

Using g++ 4.8.1 (mi

7条回答
  •  無奈伤痛
    2020-12-07 12:42

    The reason I believe this works is that the compiler does not know it is compiling the main() function so it compiles a global integer with assignment side-effects.

    The object format that this translation-unit is compiled into is not capable of differentiating between a function symbol and a variable symbol.

    So the linker happily links to the (variable) main symbol and treats it like a function call. But not until the runtime system has run the global variable initialization code.

    When I ran the sample it printed out but then it caused a seg-fault. I assume that's when the runtime system tried to execute an int variable as if it were a function.

提交回复
热议问题