error installing psycopg2, library not found for -lssl

I run

sudo pip install psycopg2

and I get a bunch of output that looks like:

cc -DNDEBUG -g -fwrapv -Os .....
.....
cc -DNDEBUG -g -fwrapv -Os .....
.....

And at the end it says:

ld: library not found for -lssl

clang: error: linker command failed with exit code 1 (use -v to see invocation)

error: command 'cc' failed with exit status 1

----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/bz/pvj1g9xj16d10pjjgbrfl3fw0000gn/T/pip_build_root/psycopg2/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/bz/pvj1g9xj16d10pjjgbrfl3fw0000gn/T/pip-uE3thn-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/var/folders/bz/pvj1g9xj16d10pjjgbrfl3fw0000gn/T/pip_build_root/psycopg2
Storing debug log for failure in /Users/Tyler/Library/Logs/pip.log

Running easy_install or doing it from source both give me the same error at the end (the part about library not found for -lssl).


Running brew install (or upgrade) openssl yields the below

$ brew upgrade openssl
Error: openssl-1.0.1h already installed

Can anyone help me out?


Solution 1:

For anyone looking for a solution for this on macOS Sierra 10.12 (or later, most likely): I fixed this by installing the command line tools:

xcode-select --install

After that, pip install psycopg2 should work.

If it doesn't, you could also try to link against brew's openssl:

env LDFLAGS="-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib" pip install psycopg2

with openssl installed via brew. Note that the brew link openssl --force does not work anymore:

$ brew link openssl --force                                                                                 17.5s
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

As @macho points out below if this still does not work, you might need to use the --no-cache option of pip, e.g.

env LDFLAGS="-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib" pip --no-cache install psycopg2

Remember to adjust these paths accordingly should you for instance build on ARM/Apple M1 Macs (as homebrew is installed at /opt/homebrew/); command as follows:

env LDFLAGS="-I/opt/homebrew/opt/openssl/include -L/opt/homebrew/opt/openssl/lib" pip --no-cache install psycopg2

Solution 2:

I had OpenSSL installed from brew (brew install openssl)

The following worked for me:

export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"
pip install psycopg2