在CMake中静态链接OpenSSL Crypto

时间:2019-03-14 14:32:56

标签: cmake openssl static-linking

我需要为MIPS设备制作一个交叉编译的OpenSSL。我尝试按照文档进行操作。将OPENSSL_USE_STATIC_LIBS设置为true,然后将target_link_libraries设置为所需的库文件。

CMakeLists.txt:

compileAsC99()

if(NOT ${use_http})
    message(FATAL_ERROR "program being generated without HTTP support")
endif()

set(program_c_files
    ...
)

set(program_h_files
    ...
)

include_directories(...)

add_executable(program ${program_c_files} ${program_h_files})

set(OPENSSL_USE_STATIC_LIBS TRUE)
#target_link_libraries(program OpenSSL::Crypto)
target_link_libraries(program /home/program/mips/lib/libssl.so.1.1)
target_link_libraries(program /home/program/mips/lib/libcrypto.so.1.1)

它可以正常编译而没有警告,但是检查生成的二进制文件告诉我它仍然是共享库。

readelf -d程序:

Dynamic section at offset 0x1bc contains 35 entries:
  Tag        Type                         Name/Value
 0x00000001 (NEEDED)                     Shared library: [libssl.so.1.1]
 0x00000001 (NEEDED)                     Shared library: [libcrypto.so.1.1]
 0x0000000f (RPATH)                      Library rpath: [/home/program/mips/lib]

我不明白我在做什么错。

编辑:已经查看了Linking statically OpenSSL crypto library in CMake,但没有告诉我任何新内容。

编辑2:根据回复更新了CMakeLists.txt文件: CMakeLists.txt:

compileAsC99()

if(NOT ${use_http})
    message(FATAL_ERROR "program being generated without HTTP support")
endif()

set(program_c_files
    ...
)

set(program_h_files
    ...
)

include_directories(...)

add_executable(program ${program_c_files} ${program_h_files})

find_package(OpenSSL REQUIRED)
if(OPENSSL_FOUND)
set(OPENSSL_USE_STATIC_LIBS TRUE)
message("OPENSSL FOUND!")
endif()
target_link_libraries(program OpenSSL::Crypto)

输出:

-- IoT Client SDK Version = 1.2.11
-- Provisioning client OFF
-- target architecture: GENERIC
-- Cross compiling not using pkg-config
-- Found CURL: /home/program/mips/lib/libcurl.a (found version "7.63.0")
-- Found CURL: /home/program/mips/lib/libcurl.a
-- target architecture: GENERIC
-- target architecture: GENERIC
-- target architecture: GENERIC
-- target architecture: GENERIC
-- iothub architecture: GENERIC
OPENSSL FOUND!
-- Configuring done
-- Generating done

编辑能力: 如果您以后的人遇到undefined reference to dlopen,我将以下内容添加到我的CMakeLists.txt文件中

target_link_libraries(program ${CMAKE_DL_LIBS})

1 个答案:

答案 0 :(得分:1)

设置为TRUE,变量OPENSSL_USE_STATIC_LIBS强制find_package(OpenSSL)搜索静态库。因此,此变量仅适用于该调用,并且如果您使用其结果:

set(OPENSSL_USE_STATIC_LIBS TRUE)
find_package(OpenSSL REQUIRED)
target_link_libraries(program OpenSSL::Crypto)

如果您已经执行cmake而未设置OPENSSL_USE_STATIC_LIBS,则需要在尝试新操作之前删除CMake缓存(在构建目录下的CMakeCache.txt)。否则,将使用已经找到的(共享!)库,并且不会执行任何重新搜索。