11

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?

1 Answer 1

13

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.

3
  • 2
    This does not answer the question, does it? The question is about linking glibc statically, and the answer explains how to link libgcc and libstdc++ statically... May 14, 2020 at 10:18
  • 1
    My answer does now. May 18, 2021 at 16:42
  • 1
    Thanks for the edit :). Good point about glibc not being designed to be statically linked, too! Finally I would like to mention musl that may be a viable alternative depending on the use-case May 18, 2021 at 22:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.