MacOS中编译时找不到OpenSSL头文件的解决方案

in with 1 comment

如题,记录一下在 macOS High Sierra 中编译代码找不到OpenSSL头文件的解决方案

错误来源

在安装 Perl 模块 Crypt::OpenSSL::Bignum 的时候,一直在报错,日志如下:

cc -c   -arch x86_64 -arch i386 -g -pipe -fno-common -DPERL_DARWIN -fno-strict-aliasing -fstack-protector -Os   -DVERSION=\"0.09\" -DXS_VERSION=\"0.09\"  "-I/System/Library/Perl/5.18/darwin-thread-multi-2level/CORE"  -DPERL5 -DOPENSSL_NO_KRB5 Bignum.c
Bignum.xs:5:10: fatal error: 'openssl/err.h' file not found
#include <openssl/err.h>
         ^~~~~~~~~~~~~~~
1 error generated.
make: *** [Bignum.o] Error 1
-> FAIL Installing Crypt::OpenSSL::Bignum failed. See /Volumes/Akvo/.cpanm/work/1530693447.26452/build.log for details. Retry with --force to force install it.
-> FAIL Installing the dependencies failed: Module 'Crypt::OpenSSL::Bignum' is not installed
-> FAIL Bailing out the installation for Webqq-Encryption-1.7.

显而易见,是没有找到 OpenSSL 的头文件导致。

解决方案

虽然 MacOS 已经自带了 OpenSSL ,但是我们依旧需要执行以下代码以安装新版。

brew install openssl

别着急,安装后会看见如下提示

A CA file has been bootstrapped using certificates from the SystemRoots
keychain. To add additional certificates (e.g. the certificates added in
the System keychain), place .pem files in
  /usr/local/etc/openssl/certs

and run
  /usr/local/opt/openssl/bin/c_rehash

This formula is keg-only, which means it was not symlinked into /usr/local,
because Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries.

If you need to have this software first in your PATH run:
  echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.zshrc

For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/openssl/lib
    CPPFLAGS: -I/usr/local/opt/openssl/include

意思就是,这个自行安装的新版并不会覆盖掉系统自带的版本。如果你希望你的程序优先调用这个版本,需要自行将之链接到环境变量;如果需要使用此版本编译软件,则需要自行在 Makefile 中设置 LDFLAGS 与 CPPFLAGS 。
当然这么做依旧是过于麻烦,经查阅资料,有网友给出解决方案:

brew link openssl --force

但是经过测试后发现 brew 拒绝链接,提示如下:

Warning: Refusing to link: openssl
Linking keg-only openssl means you may end up linking against the insecure,
deprecated system OpenSSL while using the headers from Homebrew's openssl.
Instead, pass the full include/library paths to your compiler e.g.:
  -I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib

但是我们依旧可以手动解决这个问题。
通过 brew 安装的 OpenSSL 的头文件位于 /usr/local/Cellar/openssl/版本号/include/openssl 文件夹内,以我的版本为例,即 /usr/local/Cellar/openssl/1.0.2o_2/include/openssl ,在终端内执行下列代码:

ln -s /usr/local/Cellar/openssl/1.0.2o_2/include/openssl /usr/local/include

手动创建软连接即可。然后再次执行

cpanm Crypt::OpenSSL::Bignum

就可以顺利地安装成功了。

Responses / Cancel Reply
  1. 谢谢分享,找了好久才找到解决办法

    Reply