Install Cosmopolitan on Ubuntu 24.04

Install Cosmopolitan on Ubuntu 24.04

Cosmopolitan is a toolchain that enables C code to be compiled into a single binary that can run on multiple operating systems without modification. It effectively makes C a build-once run-anywhere language, similar to how Java's bytecode works across different platforms. This tutorial explains how to install Cosmopolitan on Ubuntu 24.04.

Install Cosmopolitan

Obtain the most recent Cosmopolitan version from its GitHub repository:

COSMOPOLITAN_VERSION=$(curl -s "https://api.github.com/repos/jart/cosmopolitan/releases/latest" | grep -Po '"tag_name": "\K[0-9.]+')

Download Cosmopolitan with the version identified earlier:

wget -qO cosmopolitan.zip https://github.com/jart/cosmopolitan/releases/latest/download/cosmocc-${COSMOPOLITAN_VERSION}.zip

Extract the archive file to the /opt/cosmopolitan directory:

sudo unzip -q cosmopolitan.zip -d /opt/cosmopolitan

We need to define the directory containing Cosmopolitan binaries. Include /opt/cosmopolitan/bin in the system's PATH environment variable, which can be configured in the /etc/profile file. By doing so, the Cosmopolitan command will be accessible as a system-wide command to all users. Execute the following command to accomplish this task:

echo 'export PATH=$PATH:/opt/cosmopolitan/bin' | sudo tee -a /etc/profile

To apply the changes immediately to the current session, use the following command. Alternatively, log out and log back in to ensure the changes take effect.

source /etc/profile

Verify the installation by checking the Cosmopolitan version:

cosmocc --version

The archive file is no longer needed, remove it:

rm -rf cosmopolitan.zip

Testing Cosmopolitan

Create a main.c file:

nano main.c

Add the following code:

#include <stdio.h>

int main() {
    printf("Hello world\n");

    return 0;
}

Compile a code:

cosmocc main.c -o test

Run a program:

./test

Uninstall Cosmopolitan

To uninstall Cosmopolitan entirely, delete the installation directory:

sudo rm -rf /opt/cosmopolitan

Remove entry from /etc/profile file:

sudo sed -i '/export PATH=\$PATH:\/opt\/cosmopolitan\/bin/d' /etc/profile

Leave a Comment

Cancel reply

Your email address will not be published.