首先我要使用
#include <openssl/evp.h>
我遇到了常见的链接器错误:
undefined reference to `EVP_CIPHER_CTX_new'
我知道的可以通过在编译时使用-lcrypto
来解决。手动编译
g++ encrv2.cpp -o encrv2 -lcrypto
尽管我试图创建一个Makefile并将加密/解密功能放在单独的头文件(AesGcm)中,但无法解决链接器问题。下面是到目前为止的我的Makefile和我尝试全部制作时的输出。
CXX = g++
CXXFLAGS = -std=c++14
LDFLAGS= -lcrypto
all: encrv2
AesGcm.o: AesGcm.cpp AesGcm.h
$(CXX) $(CXXFLAGS) -c AesGcm.cpp $(LDFLAGS)
encrv2.o: encrv2.cpp AesGcm.h
$(CXX) $(CXXFLAGS) -c encrv2.cpp $(LDFLAGS)
encrv2: encrv2.o AesGcm.o
clean:
rm -f *~ *.o encrv2
出现以下错误:
cc -lcrypto encrv2.o AesGcm.o -o encrv2
AesGcm.o: In function `AesGcm::encrypt(unsigned char*, int, unsigned char*, int, unsigned char*, unsigned char*, unsigned char*, unsigned char*)':
AesGcm.cpp:(.text+0x3e): undefined reference to `EVP_CIPHER_CTX_new'
AesGcm.cpp:(.text+0x58): undefined reference to `EVP_aes_256_gcm'
AesGcm.cpp:(.text+0x77): undefined reference to `EVP_EncryptInit_ex'
AesGcm.cpp:(.text+0xae): undefined reference to `EVP_EncryptInit_ex'
AesGcm.cpp:(.text+0xe0): undefined reference to `EVP_EncryptUpdate'
AesGcm.cpp:(.text+0x111): undefined reference to `EVP_EncryptUpdate'
AesGcm.cpp:(.text+0x148): undefined reference to `EVP_EncryptFinal_ex'
AesGcm.cpp:(.text+0x17b): undefined reference to `EVP_CIPHER_CTX_ctrl'
AesGcm.cpp:(.text+0x197): undefined reference to `EVP_CIPHER_CTX_free'
AesGcm.o: In function `AesGcm::decrypt(unsigned char*, int, unsigned char*, int, unsigned char*, unsigned char*, unsigned char*, unsigned char*)':
AesGcm.cpp:(.text+0x30a): undefined reference to `EVP_CIPHER_CTX_new'
AesGcm.cpp:(.text+0x324): undefined reference to `EVP_aes_256_gcm'
AesGcm.cpp:(.text+0x343): undefined reference to `EVP_DecryptInit_ex'
AesGcm.cpp:(.text+0x37a): undefined reference to `EVP_DecryptInit_ex'
AesGcm.cpp:(.text+0x3ac): undefined reference to `EVP_DecryptUpdate'
AesGcm.cpp:(.text+0x3dd): undefined reference to `EVP_DecryptUpdate'
AesGcm.cpp:(.text+0x410): undefined reference to `EVP_CIPHER_CTX_ctrl'
AesGcm.cpp:(.text+0x441): undefined reference to `EVP_DecryptFinal_ex'
AesGcm.cpp:(.text+0x450): undefined reference to `EVP_CIPHER_CTX_free'
collect2: error: ld returned 1 exit status
<builtin>: recipe for target 'encrv2' failed
make: *** [encrv2] Error 1
答案 0 :(得分:2)
您使用了错误的变量。
LDFLAGS
用于链接标志,例如-L
等,它们需要在链接行中“更早”出现。该变量无意将库添加到链接行。
您应该为此使用LDLIBS
变量:
LDLIBS = -lcrypto
默认的链接规则是这样的,因为您自己不会自己写,所以看起来像这样:
%: %.o
# recipe to execute (built-in):
$(CC) $(LDFLAGS) $(TARGET_ARCH) $^ $(LDLIBS) -o $@
请注意,LDLIBS
出现在目标文件之后 ,这是避免此链接器错误所需要的。目标文件与库的顺序以及库本身之间的顺序对于链接器非常重要。