对 OpenSSL_version 的未定义引用,链接 openssl 时出错?

undefined reference to OpenSSL_version, Error linking openssl?

尝试运行这个简单的程序

#include <openssl/ssl.h>
int main() {
    printf("version: %s\n", OpenSSL_version(0));
    return 0;
}

结果出现这个错误

Scanning dependencies of target main
[ 50%] Building C object CMakeFiles/main.dir/main.c.o
[100%] Linking C executable main
/usr/bin/ld: CMakeFiles/main.dir/main.c.o: in function `main':
/home/khaled/CLionProjects/untitled2/main.c:4: undefined reference to `OpenSSL_version'
collect2: error: ld returned 1 exit status
make[3]: *** [CMakeFiles/main.dir/build.make:84: main] Error 1
make[2]: *** [CMakeFiles/Makefile2:105: CMakeFiles/main.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:112: CMakeFiles/main.dir/rule] Error 2
make: *** [Makefile:131: main] Error 2

我是运行局ubuntu20.04

cmakelist.txt

cmake_minimum_required(VERSION 3.16)
project(untitled2 C)

set(CMAKE_C_STANDARD 99)
add_executable(main main.c)

我想链接没有错误,因为 openssl 已经在 usr/include 中,后者又在预处理器搜索树中。我是 cmake 的新手,所以任何解释都将不胜感激。

target_link_libraries(main /usr/include/openssl/ssl.h)

不正确,因为您传递的是 header,而不是图书馆。

查看文档:

https://cmake.org/cmake/help/latest/command/target_link_libraries.html

target_link_libraries(<target> ... <item>... ...)

在您的情况下,<item> 应为库名称或库的完整路径。

您可能缺少 s/t 喜欢:

find_package(OpenSSL REQUIRED)
target_link_libraries(main PUBLIC OpenSSL::SSL OpenSSL::Crypto)