How to compile a smallest C application?

2024-09-08

We will use many different binary libraries in Linux development. For example: glibc and other third parts binary libraries. Some people maybe curiosity how to compile a program without third parts libraries? Does the main function is the first executed function? I will give you a deterministic answer by examples.

bar.c

extern void foo(void);
int _start(void) {
    foo();
    return 0;
}

The above _start function is the entrance of a program. why not is main function? Hence, we can define the entrance function through gcc parameters. However, custom entrance function is not the first code be executed. There are some loading codes and linking codes before it. If you are programming for embedded, custom entrance function is the first code be executed.

foo.s

.global foo
foo:
    movl $1, %eax       # write (
    movl $1, %edi       #   fd=1,
    movq $s, %rsi       #   buf=s,
    movl $(e-s), %edx   # count=e-s,
    syscall             # );

    movl $60, %eax      # exit (
    movl $1, %edi       #   status=1
    syscall             # );

s:
    .ascii ""\033[01;31mHello, world\033[0m\n"";
e:

The above codes is a function that prints out a string to the stdout through system call.

Makefile


all: foobar

foobar: foo.o bar.o
	ld -e _start -o $@ $^

%.o: %.s
	as $< -o $@

clean:
	rm -f *.o foobar

We can define a entrance point by ld -e _start. The output files:

  • A static program
  • A library without linking any libraries
  • The entrance point is _start not main