Linking OpenSSL libraries to a program

2019-01-03 07:03发布

问题:

I have built OpenSSL from source (an intentionally old version; built with ./config && make && make test) and would prefer to use what I have built without doing make install to link against my program.

The command that's failing is:

gcc -Wall -Wextra -Werror -static -Lopenssl/openssl-0.9.8k/ -lssl -lcrypto 
-Iopenssl/openssl-0.9.8k/include -o myApp source1.o source2.o common.o`

And I receive a series of errors similar to:

common.c:(.text+0x1ea): undefined reference to `SSL_write'

This makes me think there's something funky with my OpenSSL. If I omit -Lopenssl/openssl-0.9.8k/ from my command, the error changes to being unable to:

/usr/bin/ld: cannot find -lssl
/usr/bin/ld: cannot find -lcrypto

Am I compiling OpenSSL incorrectly? Or how should I best resolve this?

回答1:

Silly "Linux-isms" strike again! Apparently, I need to change my command such that the -L and -l stuff is at the end like (despite what man gcc seems to indicate):

gcc -Wall -Wextra -Werror -static -o myApp source1.o source2.o common.o -Lopenssl/openssl-0.9.8k/ -lssl -lcrypto -Iopenssl/openssl-0.9.8k/include



回答2:

Why don't you want to use make install? It can copy generated binaries in the directory you want if you previously passed it to ./configure --prefix $HOME/target_library_install_directory

If you used this trick with every library you build and install, you could then add the target directory to the LIBRARY_PATH environment variable and avoid using -L option.



回答3:

If you use Autotools, or you are building an Autools project like cURL, then you should be able to use pkg-config. The idea is the Autotools package will read OpenSSL's package configuration and things will "just work" for you.

The OpenSSL package configuration library name is openssl.

You would use it like so in a makefile based project.

%.o: %.c
        $(CC) -o $@ -c `pkg-config --cflags openssl` $^

target: foo.o bar.o baz.o
        $(CC) -o $@ `pkg-config --libs openssl` $^

Also see How to use pkg-config in Make and How to use pkg-config to link a library statically.



标签: