DEV Community

Shaw
Shaw

Posted on

Cosmopolitan Libc

#c

Portable but not Small

Java was one of the first languages to emphasize cross platform binaries. It did tis with the .jar file, which is just a piece of compiled code that is executable on any platform. This does still require a Java Virtual Machine installed.

Small but not Portable

C on the other hand has never had this luxury. One would need to build C for each platform that exists. However, it allowed for C developers to ship standalone binaries that had no dependancies other than the underlying Libc.

Solution

Cosmopolitan Libc (Cosmo for short) is an implementation of Libc that runs on almost any 64 bit x86 machine. Cosmo does all this in a single binary.

The same file that runs on Linux runs on Windows runs on MacOS. Binaries built with Cosmo, however, have the same lack of dependancies as files built with a standard Libc. Cosmo is everything I love in modern C.

Example

Start with a simple hello world

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
}
Enter fullscreen mode Exit fullscreen mode

Replace all standard headers with a single

#include <cosmopolitan.h>

int main() {
    printf("Hello, World!\n");
}
Enter fullscreen mode Exit fullscreen mode

Get Cosmopolitan Libc.

wget https://justine.lol/cosmopolitan/cosmopolitan.zip
mkdir -p cosmo && cd cosmo && 7z x ../cosmopolitan.zip
Enter fullscreen mode Exit fullscreen mode

Build the .c file into a .com

gcc main.c -O2 -static -fno-pie -mno-red-zone -nostdlib \
    -nostdinc -fno-omit-frame-pointer -o main.com.dbg \
    -Wl,--gc-sections -fuse-ld=bfd -Wl,-T,cosmo/ape.lds \
    cosmo/crt.o cosmo/ape.o cosmo/cosmopolitan.a \
    -Icosmo
objcopy -S -O binary main.com.dbg main.com
Enter fullscreen mode Exit fullscreen mode

Run the .com file.

chmod +x main.com
env ./main.com
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
pauljlucas profile image
Paul J. Lucas

The URL for Cosmo is wrong.

Collapse
 
shawsumma profile image
Shaw

It should be fixed now... Im not sure how that happened.
Thanks for telling me!