Calling some functions before main in C

后端 未结 4 1310
孤独总比滥情好
孤独总比滥情好 2020-12-06 07:15

I\'d like to do some stuffs before main function. I have multiple source files. In each file, there is some work that needs to be done before main.

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 07:55

    Assuming you are not mixing C++ in with your C... (because then you could do the static constructors on your c++ class, which is maybe what you're asking!)

    Crt0 is the platform-specific runtime setup traditionally called before main(). You could override that, but that's pretty deep.

    Some embedded platforms provide a _pre_main() and _post_main() kind of procs. But that's nonstandard I think.

    Really, your main entry point is, well, main()!

    If you're in control of the Makefile, you could force main to be something else, with something like

    gcc app.c -Dmain=not_really_main
    

    And then link in your real main() to call not_really_main().


    edit: one more approach: The gcc linker has a variable called ENTRY which is the first thing executed, usually crt0. Again, this is pretty heavyweight, and you'll have understand the platform pretty deeply to pull it off, but it's another place you can "subvert main".

提交回复
热议问题