in c++ main function is the entry point to program how i can change it to an other function?

前端 未结 13 1828
忘了有多久
忘了有多久 2020-12-03 01:12

I was asked an interview question to change the entry point of a C or C++ program from main() to any other function. How is it possible?

相关标签:
13条回答
  • 2020-12-03 01:26

    I think it is easy to remove the undesired main() symbol from the object before linking.

    Unfortunately the entry point option for g++ is not working for me(the binary crashes before entering the entry point). So I strip undesired entry-point from object file.

    Suppose we have two sources that contain entry point function.

    1. target.c contains the main() we do not want.
    2. our_code.c contains the testmain() we want to be the entry point.

    After compiling(g++ -c option) we can get the following object files.

    1. target.o, that contains the main() we do not want.
    2. our_code.o that contains the testmain() we want to be the entry point.

    So we can use the objcopy to strip undesired main() function.

    objcopy --strip-symbol=main target.o

    We can redefine testmain() to main() using objcopy too.

    objcopy --redefine-sym testmain=main our_code.o

    And then we can link both of them into binary.

    g++ target.o our_code.o -o our_binary.bin

    This works for me. Now when we run our_binary.bin the entry point is our_code.o:main() symbol which refers to our_code.c::testmain() function.

    0 讨论(0)
  • 2020-12-03 01:28

    Modify the crt object that actually calls the main() function, or provide your own (don't forget to disable linking of the normal one).

    0 讨论(0)
  • 2020-12-03 01:28

    On windows there is another (rather unorthodox) way to change the entry point of a program: TLS. See this for more explanations: http://isc.sans.edu/diary.html?storyid=6655

    0 讨论(0)
  • 2020-12-03 01:28

    Yes, We can change the main function name to any other name for eg. Start, bob, rem etc.

    How does the compiler knows that it has to search for the main() in the entire code ?

    Nothing is automatic in programming. somebody has done some work to make it looks automatic for us.

    so it has been defined in the start up file that the compiler should search for main().

    we can change the name main to anything else eg. Bob and then the compiler will be searching for Bob() only.

    0 讨论(0)
  • 2020-12-03 01:29

    If you are on VS2010, this could give you some idea

    As it is easy to understand, this is not mandated by the C++ standard and falls in the domain of 'implemenation specific behavior'.

    0 讨论(0)
  • For Solaris Based Systems I have found this. You can use the .init section for every platforms I guess:

       pragma init (function [, function]...)
    

    Source:

    This pragma causes each listed function to be called during initialization (before main) or during shared module loading, by adding a call to the .init section.

    0 讨论(0)
提交回复
热议问题