How to Build an Application with Your Own Custom GLibC

Suppose you have downloaded the source for some version of glibc, perhaps modified it yourself, built it, and installed it in your own user directory--say, /home/my_acct/glibc_install. Now suppose you want to build an application linked statically against your custom version of glibc rather than your system's default glibc. (Suppose also that you are using your system's installation of GCC.) This sounds like a simple task, but it can be a bit tricky. The key idea is to tell the linker to omit all of the files that it normally includes automatically (and silently) by defaut, and then to include back all the files it needs to complete building your executable. Some of these files--including, naturally, libc.a--are in your custom-build directory (here, /home/my_acct/glibc_install/lib); while others come from a directory associated with the GCC you are using--in this example, your system's default GCC. Below is a sample makefile to serve as a template. It assumes that you wish to build a program prog, in the same directory as the makefile, out of source file prog.c.

TARGET = prog
CC = gcc
LDFLAGS = -nostdlib -nostartfiles -static
GLIBCDIR = /home/my_acct/glibc_install/lib
STARTFILES = $(GLIBCDIR)/crt1.o $(GLIBCDIR)/crti.o `gcc --print-file-name=crtbegin.o`
ENDFILES = `gcc --print-file-name=crtend.o` $(GLIBCDIR)/crtn.o
LIBGROUP = -Wl,--start-group $(GLIBCDIR)/libc.a -lgcc -lgcc_eh -Wl,--end-group

        $(CC) $(LDFLAGS) -o $@ $(STARTFILES) $^ $(LIBGROUP) $(ENDFILES) 
$(OBJ): $(SRC)
        $(CC) $(CFLAGS) -c $^

        rm -f *.o *.~ $(TARGET)