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

后端 未结 3 1381
一生所求
一生所求 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 01:08

    C

    Sure. Simply go ahead and do it.

    #include 
    
    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 
    
    int main()
    {
       std::cout << (void*)&main << '\n';
    }
    

    You will receive a warning that this is not compliant.

提交回复
热议问题