In a C/C++ program how does the system (windows, linux, mac OS X) call the main() function

前端 未结 7 1501
半阙折子戏
半阙折子戏 2020-12-09 03:51

I am looking for a more technical explanation then the OS calls the function. Can anyone help me out or point me to a website or book?

7条回答
  •  感动是毒
    2020-12-09 04:36

    It's OS dependent. In OS X, there's a frame in the mach header that contains the start address for the EIP (instruction pointer) register.

    Once the binary is loaded, the OS launches execution from this address:

    cristi:test diciu$ otool -l ./a.out | grep -A 10 LC_UNIXTHREAD
            cmd LC_UNIXTHREAD
        cmdsize 80
         flavor i386_THREAD_STATE
          count i386_THREAD_STATE_COUNT
    [..]
            ss  0x00000000 eflags 0x00000000 eip 0x00001f8c cs  0x00000000
    [..]
    

    The address is the address of the "start" function from the binary:

    cristi:test diciu$ nm ./a.out
    0000200c D _NXArgc
    00002008 D _NXArgv
    00002000 D ___progname
    00001fe0 t __dyld_func_lookup
    00001000 A __mh_execute_header
    [..]
    00001f8c T start
    

    In Mac OS X, it's the "start" function that gets called first, even before the "main" function:

    (gdb) b start
    Breakpoint 1 at 0x1f90
    (gdb) b main
    Breakpoint 2 at 0x1ff4
    (gdb) r
    Starting program: /Users/diciu/Programming/test/a.out 
    Reading symbols for shared libraries ++. done
    
    Breakpoint 1, 0x00001f90 in start ()
    

提交回复
热议问题