cosmopolitan libc

your build-once run-anywhere c library

Cosmopolitan Libc makes C a build-once run-anywhere language, like Java, except it doesn't need an interpreter or virtual machine. Instead, it reconfigures stock GCC and Clang to output a POSIX-approved polyglot format that runs natively on Linux + Mac + Windows + FreeBSD + OpenBSD + NetBSD + BIOS with the best possible performance and the tiniest footprint imaginable.

Getting Started

Assuming you have GCC on Linux, then all you need are the five additional files which are linked below:

# create simple c program on command line
printf %s '
  main() {
    printf("hello world\n");
' >hello.c

# run gcc compiler in freestanding mode
gcc -g -Os -static -fno-pie -no-pie -nostdlib -nostdinc -gdwarf-4 \
  -fno-omit-frame-pointer -pg -mnop-mcount -mno-tls-direct-seg-refs \
  -o hello.com.dbg hello.c -Wl,--gc-sections -fuse-ld=bfd -Wl,--gc-sections \
  -Wl,-T,ape.lds -include cosmopolitan.h crt.o ape-no-modify-self.o cosmopolitan.a
objcopy -S -O binary hello.com.dbg hello.com

# NOTE: scp it to windows/mac/etc. *before* you run it!
# ~40kb static binary (can be ~16kb w/ MODE=tiny)

The above command fixes GCC so it outputs portable binaries that will run on every Linux distro in addition to Mac OS X, Windows NT, FreeBSD, OpenBSD, and NetBSD too. For details on how this works, please read the αcτµαlly pδrταblε εxεcµταblε blog post. This novel binary format is also optional, since hello.com.dbg is executable too, only on your local system since it's an ELF binary.

Your program will also boot on bare metal too. In other words, you've written a normal textbook C program, and thanks to Cosmopolitan's low-level linker magic, you've effectively created your own operating system which happens to run on all the existing ones as well. Now that's something no one's done before.