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 was asked an interview question to change the entry point of a C
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In standard C (and, I believe, C++ as well), you can’t, at least not for a hosted environment (but see below). The standard specifies that the starting point for the C code is
main. The standard (c99) doesn’t leave much scope for argument:That’s it. It then waffles on a bit about parameters and return values but there’s really no leeway there for changing the name.
That’s for a hosted environment. The standard also allows for a freestanding environment (i.e., no OS, for things like embedded systems). For a freestanding environment:
You can use “trickery” in C implementations so that you can make it look like
mainisn’t the entry point. This is in fact what early Windows compliers did to markWinMainas the start point.First way: a linker may include some pre-main startup code in a file like
start.oand it is this piece of code which runs to set up the C environment then callmain. There’s nothing to stop you replacing that with something that callsbobinstead.Second way: some linkers provide that very option with a command-line switch so that you can change it without recompiling the startup code.
Third way: you can link with this piece of code:
and then your entry point for your code is seemingly
bobrather thanmain.However, all this, while of possibly academic interest, doesn’t change the fact that I can’t think of one single solitary situation in my many decades of cutting code, where this would be either necessary or desirable.
I would be asking the interviewer: why would you want to do this?