Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a main() required for a C program?

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.

like image 827
elricL Avatar asked Nov 06 '10 15:11

elricL


People also ask

Can a program run without main () in C?

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.

What happens without main () function in C program?

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.


2 Answers

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.

like image 69
paxdiablo Avatar answered Sep 16 '22 12:09

paxdiablo


Well, no, but ...

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.

like image 43
DigitalRoss Avatar answered Sep 20 '22 12:09

DigitalRoss