OpenSSL

一些C/CPP项目,在代码中使用HTTPS协议访问网站,需要使用OpenSSL的.h原文件和SSL库,在编译的时候需要连接这两个资源。

在Mac OS上,默认安全的不是通常意义上的开源的OpenSSL, 需要我们手动通过brew进行安装。

brew install  openssl

在CPP编译时要指明.h的位置和库文件的位置。通过-I和-L两个参数。

查看OpenSSL的.h文件位置、库文件的位置,使用命令,如下:

brew info openssl

我们用一个CPP项目,开展示编译参数的使用。

git clone https://github.com/AntiSomnus/iDict-cmd.git

g++ -Os -m64 -std=c++14 idict_linux.cpp -o idict -lssl -lcrypto -v $LDFLAGS

为了让主程序连接时,可以找到OpenSSL的-lssl这个参数,对应的库文件,加了$LDFLAGS这个参数。这个参数等同于,如下:

-L/opt/homebrew/opt/openssl

这路径通过brew info openssl查看,结果类似,如下:

==> openssl@3: stable 3.0.7 (bottled) [keg-only]
Cryptography and SSL/TLS Toolkit
https://openssl.org/
/opt/homebrew/Cellar/openssl@3/3.0.7 (6,454 files, 28.0MB)
  Poured from bottle on 2023-01-13 at 11:02:26
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/openssl@3.rb
License: Apache-2.0
==> Dependencies
Required: ca-certificates ✔
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /opt/homebrew/etc/openssl@3/certs

and run
  /opt/homebrew/opt/openssl@3/bin/c_rehash

openssl@3 is keg-only, which means it was not symlinked into /opt/homebrew,
because macOS provides LibreSSL.

If you need to have openssl@3 first in your PATH, run:
  echo 'export PATH="/opt/homebrew/opt/openssl@3/bin:$PATH"' >> ~/.zshrc

For compilers to find openssl@3 you may need to set:
  export LDFLAGS="-L/opt/homebrew/opt/openssl@3/lib"
  export CPPFLAGS="-I/opt/homebrew/opt/openssl@3/include"

For pkg-config to find openssl@3 you may need to set:
  export PKG_CONFIG_PATH="/opt/homebrew/opt/openssl@3/lib/pkgconfig"

==> Analytics
install: 333,606 (30 days), 736,709 (90 days), 2,116,153 (365 days)
install-on-request: 86,899 (30 days), 300,347 (90 days), 1,318,084 (365 days)
build-error: 280 (30 days)

这些返回结果中,和.h头文件,库文件,最直接相关的两个参数:CPPFLAGS和LDFLAGS。在编译的时候直接用$进行引用就可以,顺序如下:

export CPPFLAGS="-I/opt/homebrew/opt/openssl@3/include"   
export LDFLAGS="-L/opt/homebrew/opt/openssl@3/lib"
g++ -Os -m64 -std=c++14 idict_linux.cpp -o idict -lssl -lcrypto -v $LDFLAGS $CPPFLAGS

经过如上的操作,在 Mac上编译时用OpenSSL库,就很顺畅了。

因为用到加解密模块,很多其他的软件,都可能依赖OpenSLL,特别是很多的C/CPP代码项目工程。