10

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?

genpfault
  • 51,148
  • 11
  • 85
  • 139
Phạm Văn Thông
  • 743
  • 2
  • 7
  • 21

1 Answers1

12

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.

Cinder Biscuits
  • 4,880
  • 31
  • 51
  • 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... – JonasVautherin May 14 '20 at 10:18
  • 1
    My answer does now. – Cinder Biscuits May 18 '21 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 – JonasVautherin May 18 '21 at 22:43