Static executable on linux using latest CMake

I am using CMake 3.24.3.
What is the cleanest way, most modern way, to mandate a static executable?

I want to make sure that my final binary will be able to run on remote Linux servers, without worrying about the host setup, making sure that the executable will run exactly as on my system.
No more guessing.


The easiest way is to tell all dependencies to build statically. You’ll also probably want to use musl instead of glibc. For that, I would recommend building with Alpine or a similar distribution myself.

Thanks Ben,
building statically, yes, but I would like the help of Cmake as much as I can not to miss a detail.

Cmake doesn’t have a one liner of the like “CMAKE_LIBRARIES(“static”)” that would force the linker to choose .a and not .so?

No, there’s no real way to do that AFAIK. Every find_package (that supports this) would usually have their own mechanism for selecting static versus shared. You might be able to fiddle with CMAKE_FIND_LIBRARY_SUFFIXES to only let find_library find static libraries, but projects that use exported targets don’t use find_library. I think I’d add a test or something that checks whether your binary is a static executable or not at least. If you use an add_custom_command it’d run during the build, but add_test can work too.


I think Appimage is what I am after I guess.
It would overcome all the difficulties.