Linking libssl and libcrypto in GCC [duplicate]
Asked Answered
H

2

14

I'm attempting to use OpenSSL's EVP interface to do some encryption. I'm pretty sure my code is right, but I can't seem to get it to compile. I'm using GCC, and Ubuntu 32-bit precise with libssl-dev installed and at the latest version.

The project currently consists of one file, program.c.

#include <openssl/evp.h>
...
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1() ... );
...
EVP_CIPHER_CTX_init(e_ctx);

among other various calls.

Here is how I invoke gcc:

gcc -Wall -g -lssl -lcrypto -o program program.c

Then I get output like this

/home/andy/program/program.c:31: undefined reference to `EVP_sha1'
/home/andy/program/program.c:31: undefined reference to `EVP_aes_256_cbc'
/home/andy/program/program.c:31: undefined reference to `EVP_BytesToKey'
/home/andy/program/program.c:44: undefined reference to `EVP_CIPHER_CTX_init'

So the include is clearly working:

andy@ProgStation2:/usr/include$ find . | grep evp.h
./openssl/evp.h

Here is the output of locate libcrypto. My best guess is that this is a stupid location for it and is why my link is failing, so I tried -L/usr/lib/i386-linux-gnu before -lcrypto with no luck as well.

/lib/i386-linux-gnu/libcrypto.so.1.0.0

I'm kind of stumped. If anyone wants to make me feel like a fool, I'd be very excited to figure out what i'm doing wrong!

Hurley answered 16/9, 2013 at 18:54 Comment(0)
H
22

It turns out it was something stupid. In the linker step, I was using gcc -Wall -g -lssl -lcrypto -o program program.o. I needed to move the library links to after the object file I was linking, and put libssl before libcrypto:

gcc -Wall -g -o program program.o -lssl -lcrypto
Hurley answered 18/9, 2013 at 13:1 Comment(1)
Yep, order and placement matters when linking. The -l options should come at the end of the compiler driver (GCC) command. And order of the libraries matters too because ld is a single pass linker. So -lssl -lcrypto works, but -lcrypto -lssl won't work. You'll get linker errors because ld already visited libcrypto when it visits libssl (libssl needs stuff from libcrypto).Pentheam
N
-1

Try including headers using -I option, Look into directory for library using -L and finally specifying the library name with -l

Just making guess here, please specify path based on actual location.

gcc -g -Wall  -L/usr/lib -I/usr/include -lssl -lcrypto -o program program.c 

Hope it may help.

Nourishment answered 16/9, 2013 at 19:10 Comment(1)
Adding the include doesn't seem to work (though you had the path correct). I think the problem is linking to the function definitions rather than the prototypes, since it seems to make it through the compilation part, just not the linking.Hurley

© 2022 - 2024 — McMap. All rights reserved.