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

前端 未结 13 1888
忘了有多久
忘了有多久 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.

提交回复
热议问题