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?
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.
After compiling(g++ -c option) we can get the following object files.
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.
Modify the crt object that actually calls the main()
function, or provide your own (don't forget to disable linking of the normal one).
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
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.
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'.
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.