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, and I didn't see a main() function.
The answer is yes. We can write program, that has no main() function. In many places, we have seen that the main() is the entry point of a program execution. Just from the programmers perspective this is true.
C Program without main() function - Programming Puzzles It is called micro preprocessor because it allows us to add macros. A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. Here, PI is the macro name which will be replaced by the value 3.14.
No, the ISO C standard states that a main
function is only required for a hosted environment (such as one with an underlying OS).
For a freestanding environment like an embedded system (or an operating system itself), it's implementation defined. From C99 5.1.2
:
Two execution environments are defined: freestanding and hosted. In both cases, program startup occurs when a designated C function is called by the execution environment.
In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined.
As to how Linux itself starts, the start point for the Linux kernel is start_kernel though, for a more complete picture of the entire boot process, you should start here.
C99 specifies that main()
is called in the hosted environment "at program startup", however, you don't have to use the C runtime support. Your operating system executes image files and starts a program at an address provided by the linker.
If you are willing to write your program to conform to the operating system's requirements rather than C99's, you can do it without main(). The more modern (and complex) the system, though, the more trouble you will have with the C library making assumptions that the standard runtime startup is used.
Here is an example for Linux...
$ cat > nomain.S .text _start: call iamnotmain movl $0xfc, %eax xorl %ebx, %ebx int $0x80 .globl _start $ cat > demo.c void iamnotmain(void) { static char s[] = "hello, world\n"; write(1, s, sizeof s); } $ as -o nomain.o nomain.S $ cc -c demo.c $ ld -static nomain.o demo.o -lc $ ./a.out hello, world
It's arguably not "a C99 program" now, though, just a "Linux program" with a object module written in C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With