Creating Static Executables on Linux

It is difficult to create distributable executables for Linux because of issues like incompatible C libraries and C++ standard libraries. Creating static executables avoids some of  the dependencies, although it may not necessarily help with portability. Static builds are useful for other problems, as discussed in future posts. ITK Git master recently added support for building static executables.  In this post, we will describe how to build static executables against ITK.

 

When configuring ITK, use the following options:

The BUILD_SHARED_LIBS option tells CMake to build static libraries instead of shared libraries, which can be linked into the static executable. Also, the ITK_DYNAMIC_LOADING option disables ITK’s ability to load libraries at runtime into its object factory — this requires dynamic loading.

When building executables against ITK, use the following configuration,

The -static flag is passed to the linker so it will create a static executable instead of a dynamically linked executable. The CMAKE_FIND_LIBRARY_SUFFIXES variable will ensure that CMake only finds static libraries, which end it .a. In this case, it is not strictly necessary since we only built ITK with static libraries.

When we examine the executable created from a dynamic build:

we see that it is dynamically linked and uses an interpreter, i.e. the dynamic loader, /lib64/ld-linux-x86-64.so.2.  The file size is 124 kilobytes.

And the executable created from a static build:

In this case, the executable is statically linked. The disadvantage to statically linked executables is their size — 6.0 megabytes versus 124 kilobytes.  There are other important disadvantages to consider when statically linking in glibc into executables, especially when creating executables for distribution.

Enjoy ITK!

Questions or comments are always welcome!