How can a program with a global variable called ma

2019-01-16 05:57发布

Consider following program:

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

Using g++ 4.8.1 (mingw64) on Windows 7 OS, the program compiles and runs fine, printing:

C++ is excellent!

to the console. main appears to be a global variable rather than a function; how can this program execute without the function main()? Does this code conform to the C++ standard? Is the behavior of the program is well defined? I have also used the -pedantic-errors option but the program still compiles and runs.

7条回答
放荡不羁爱自由
2楼-- · 2019-01-16 06:33

gcc 4.8.1 generates the following x86 assembly:

.LC0:
    .string "C++ is excellent!\n"
    subq    $8, %rsp    #,
    movl    std::__ioinit, %edi #,
    call    std::ios_base::Init::Init() #
    movl    $__dso_handle, %edx #,
    movl    std::__ioinit, %esi #,
    movl    std::ios_base::Init::~Init(), %edi  #,
    call    __cxa_atexit    #
    movl    $.LC0, %esi #,
    movl    std::cout, %edi #,
    call    std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)   #
    movl    $195, main(%rip)    #, main
    addq    $8, %rsp    #,
    ret
main:
    .zero   4

Note that cout is called during initialization, not in the main function!

.zero 4 declares 4 (0-initialized) bytes starting at location main, where main is the name of the variable[!].

The main symbol is interpreted as the start of the program. The behavior depends on the platform.

查看更多
登录 后发表回答