Is a main() required for a C program?

后端 未结 7 463
后悔当初
后悔当初 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 03:40

    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.

提交回复
热议问题