How to static linking to glibc in cmake

Phạm Văn Thông picture Phạm Văn Thông · Oct 18, 2017 · Viewed 8.4k times · Source

I'm trying to build a package from Fedora that can run on a RedHat 6 machine. So I need to build and static linking with some library that does not exist in RedHat machine. I found that I can you -static-libgcc or -static-libstdc++ to link with static version of standard library but I don't know how to do with glibc. How can I link to static library of glibc with CMake?

Sorry for my bad English.

Answer

Cinder Biscuits picture Cinder Biscuits · Oct 18, 2017

I know the question mentions glibc but for C++, since -static-libgcc and -static-libstdc++ are linker options, the correct way to set them in CMake is with target_link_libraries().

So you would set it like this, where MyLibrary is the name of your project:

target_link_libraries(MyLibrary -static-libgcc -static-libstdc++)

Given this, if you want complete static linking of glibc you would likewise pass the -static flag.

target_link_libraries(MyLibrary -static)

If you want more of a global setting:

set(BUILD_SHARED_LIBS OFF)
set(CMAKE_EXE_LINKER_FLAGS "-static")

However, bear in mind that glibc is not designed to be statically linked, and without a great amount of additional work, you won't wind up with a truly static package. Your use case of building "a package from Fedora that can run on a RedHat 6 machine" will not readily work by statically linking glibc.