Address of function main() in C/C++

后端 未结 3 1379
一生所求
一生所求 2021-01-06 00:33

Is there a way to find out the address of main() in C or C++ ? Since it is itself a function ,would there be an address of it own ?

相关标签:
3条回答
  • 2021-01-06 00:59

    If for any system you can't find the address of main.. put an invocation to a function foo() as the only statement in main, have main return whatever it returns and use the address of foo rather than main.

    Note that calling main won't necessarily restart your code, even if there are no static/global variables. The compiler generates start up code before actually calling main.

    If you want to breakpoint before this call to main write something like:

    static int i=foo();
    

    and foo will be called during the earlier data initialisation step.

    0 讨论(0)
  • 2021-01-06 01:08

    C

    Sure. Simply go ahead and do it.

    #include <stdio.h>
    
    int main(void)
    {
       printf("%p\n", &main);
    }
    

    C++

    It is not permitted to take main's address so, for your purposes, there isn't one:

    [C++11: 3.6.1/3]: The function main shall not be used within a program. [..]

    However, in GCC you can take the same approach as you would in C, via a compiler extension:

    #include <iostream>
    
    int main()
    {
       std::cout << (void*)&main << '\n';
    }
    

    You will receive a warning that this is not compliant.

    0 讨论(0)
  • 2021-01-06 01:10

    I wasn't 100% sure whether the question was meant from within a program using C/++ or to retrieve address of the main() function created with C/C++ (meaning from the command line).

    Since it looks like you've received several good answers on how to get the address from within the program, I thought I'd mention you can get this info from nm as well.

    nm program|grep main
    
    0 讨论(0)
提交回复
热议问题