Is a main() required for a C program?

后端 未结 7 434
后悔当初
后悔当初 2020-12-15 03:13

Well the title says it all. Is a main() function absolutely essential for a C program?

I am asking this because I was looking at the Linux kernel code,

相关标签:
7条回答
  • 2020-12-15 04:03

    The operating systems loader has to call a single entry point; in the GNU compiler, the entry point is defined in the crt0.o linked object file, the source for this is the assembler file crt0.s - that invokes main() after performing various run-time start-up tasks (such as establishing a stack, static initialisation). So when building an executable that links the default crt0.o, you must have a main(), otherwise you will get a linker error since in crt0.o main() is an unresolved symbol.

    It would be possible (if somewhat perverse and unnecessary) to modify crt0.s to call a different entry point. Just make sure that you make such an object file specific to your project rather than modifying the default version, or you will break every build on that machine.

    The OS itself has its own C runtime start-up (which will be called from the bootloader) so can call any entry point it wishes. I have not looked at the Linux source, but imagine that it has its own crt0.s that will call whatever the C code entry point is.

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