This article was published on February 4th 2019 and takes about 2 minutes to read.
Compiling a Crystal project with static linking allows you to easily distribute it as a single file without any dependencies. Unfortunately, right not it is only possible on Alpine Linux machines. I'll show you how it's done.
Why I am such a fan will be topic for another article, but being able to compile a Crystal project to a single binary is — besides its syntax and ideology closely resembling Ruby's — clearly the number one reason.
Crystal compiles with dynamic linking per default. This is no problem most of the time — compiling a Crystal project on CentOS, copying the resulting binary to a Ubuntu mache and running it there simply works. That's because they share the same dynamic libraries Crystal links to on compilation.
Things get a little trickier once you want to package your compiled Crystal project into an RPM: The
rpmbuild command throws a dependency issue which is impossible to resolve at the moment.
This is where static linking comes into play.
The Crystal docs have sad news on static linking currently:
Static linking using the
--staticcompiler flag is currently only supported on Alpine Linux. The easiest way to do this is to compile your application inside an Alpine Linux Docker container.
Firing up a Docker container for the sole purpose of compiling your project only pays if you already use Docker in your workflow.
If you are one of many developers who don't, you can either build your own Alpine Linux virtual machine (which is even more work) or simply use my prebuilt Vagrant box.
After creating a Vagrantfile with
vagrant init relativkreativ/alpine-3 and running
vagrant up there is a little work left to do before we can compile our Crystal project:
apk add crystal shardsas root to install all packages related to Crystal. These packages are served from the community repository (which is already enabled in
/etc/apk/repositoriesfor my box).
apk add libc-dev(which is a meta package which does just that).
Once this is done, you can compile your Crystal project with
crystal build src/FILE.cr -o bin/FILE --release --static.
This article refers to Crystal 0.27.1.