通过CMake 2.8静态链接Linux C ++应用程序

时间:2016-03-14 17:37:36

标签: c++ linux cmake

我的应用程序内置在Ubuntu 14.04 / GCC 4.8 / CMake 2.8中,带有-static-libgcc和-static-libstdc ++。 ldd命令显示:

linux-vdso.so.1 =>  (0x00007ffc16195000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fcb18256000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fcb17f50000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fcb17b8a000)
/lib64/ld-linux-x86-64.so.2 (0x000055fc367e1000)

当我向CMAKE_EXE_LINKER_FLAGS添加-static时 - 我从ldd获得了不同的输出:

linux-vdso.so.1 =>  (0x00007ffd48349000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fe8d0335000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fe8d0031000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fe8cfd2a000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fe8cf965000)
/lib/ld64.so.1 => /lib64/ld-linux-x86-64.so.2 (0x000055d61ec7d000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fe8cf74f000)

我认为-static标志会导致静态链接应用程序。它没有发生。 愿任何人解释我的原因吗?

我有Qt Creator生成的makefile - 使用-static开关构建会产生完全静态的应用程序。

2 个答案:

答案 0 :(得分:0)

-static-static-libgcc-static-libstdc++不同,因为-static不承担标准库的静态链接。这两个标志控制了这种行为。

要与标准库静态链接,请将这两个标志添加到CMake CMAKE_EXE_LINKER_FLAGS变量。

答案 1 :(得分:0)

来自生成的CMakeLists.txt。我在运行CMake时使用-DSTATIC_LINKING = True。

IF(STATIC_LINKING)
    SET(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
ENDIF(STATIC_LINKING)


# libpcap library
find_library(pcap libpcap.a)

# opencore-amr libraries
find_library(opencore-amrnb libopencore-amrnb.a)
find_library(opencore-amrwb libopencore-amrwb.a)

# c++ netlib
find_library(cppnetlib-server-parsers libcppnetlib-server-parsers.a)
find_library(cppnetlib-uri libcppnetlib-uri.a)
find_library(cppnetlib-client-connections libcppnetlib-client-connections.a)

# pthread
find_library(pthread libpthread.a)

# boost libraries
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)

# set -static, when STATIC_LINKING is TRUE and set LINK_SEARCH_END_STATIC
# to remove the additional -bdynamic from the linker line.
IF(STATIC_LINKING)
    SET(CMAKE_EXE_LINKER_FLAGS "-static -static-libgcc -static-libstdc++"
    SET_TARGET_PROPERTIES(pvqa-server PROPERTIES LINK_SEARCH_END_STATIC 1)
ENDIF(STATIC_LINKING)