Search code examples
clinuxmallocheader-files

How to compile my version of Malloc in C?


I'm currently coding my implementation of the malloc() function, so I'm compiling with the following flags: -m64 -fPIC -pedantic -Wall -Wextra -Werror -nostdlib -ggdb3.

For the time being, I'm compiling as an executable and not as a shared library.

For my implementation I'm using the header files stddef.h stdint.h unistd.h, for the moment I need the syscall sbrk(). The problem is that on compilation I get the following error: undefined reference to sbrk.

I assume that sbrk() and more generally unistd.h are disabled if I compile with -nostdlib but how can I compile without the glibc but with the system calls?

Thanks in advance

P.S I really need to use sbrk() I can't use mmap(), don't encourage me to do it.


Solution

  • If you're doing what it sounds like you are trying to do, then you will eventually have to write your own implementation of all of the C library functionality that you need. However, a stepping stone in that direction is to compile your semi-freestanding program like this:

    gcc -c -ffreestanding [other options] -o foo.o foo.c
    # ... repeat the above for all other object files ...
    
    gcc -ffreestanding -nostdlib -nostartfiles -static -o yourprogram \
        foo.o [other objects] -lc -lgcc
    

    This tells the C implementation to supply only the parts of the standard libraries that you actually use yourself. Note that many standard APIs will not work correctly in this mode; don't use anything from stdio.h, nor anything locale-dependent (as the C standard uses that term), nor anything to do with threads. The system call wrappers should be fine, though, as should most of string.h.