简体   繁体   中英

How do I obtain a function pointer to the main() method in C++?

I'm working on MS C++ compiler, and have done the next program:

#include <stdio.h>

void main(void)
{
    void(*ptr)(void) = &main;
}

I wanted to make a pointer on main() method/function, but has got the next error:

error C2440: 'initializing' : cannot convert from 'int (__cdecl *)(void)' to 'void (__cdecl *)(void)'
This conversion requires a reinterpret_cast, a C-style cast or function-style cast

I wonder:

  • how can I get the pointer of function/method main()
  • why by default in output is info about int __decl..., but I have exactly wrote void on main() , not int?

Here's how to obtain a pointer to the main function:

#define DECLARE_UNUSED( name ) (void) name;  struct name

int main()
{
    int(*ptr)() = &main;
    DECLARE_UNUSED( ptr );    // Prevents using `ptr`.
    // Don't use `ptr` here. In particular, don't call.
}

Note that

  • main must have result type int .

  • calling main (eg via that pointer) incurs Undefined Behavior.

  • It is not necessary to return anything from main ; the default return value is 0.

As you can see main is a very special function.

Those rules do not (in general) apply to other functions.

Also note that Visual C++ is wrong in not diagnosing void result type.

Finally, note that writing non-standard void is one character more to type than standard int , ie, it is just a very, very dumb thing to do. ;-)

PS: Visual C++ is probably mumbling things about int main because it (probably) translates void main to int main internally, and probably it does that to make things link with a non-intelligent linker while actively supporting void main so that eg Microsoft's own non-standard examples in their documentation will compile. That's my theory #1 anyway, since you ask. But it is, of course, pure guesswork, and it may be that even those who coded that up have no clear idea of why (theory #2).

Well, if you really want to change the entry point of an executable, find the Optional Header by following the steps here, offset 16 bytes and change the 4 bytes. You can find the PE specification here . In order to change the executable file itself while running, you will need some assembly trick, or emit another executable, run a batch and kill the running process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM