如何使用OpenSSL编译简单程序?

dr.*_*oom 3 c++ gcc openssl compilation ld

我正在尝试编译一个简单的ssl程序(它取自openssl书的源代码)。该程序具有以下文件:common.h common.c client.c server.c

我已经安装了openssl 0.9.7,因此与本书具有相同的版本。我已经下载了源代码并在主目录中进行./Configure、make、make test,make install。

common.h中包括以下内容:

#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h> 
Run Code Online (Sandbox Code Playgroud)

我运行gcc -Wall common.c client.c -o client但出现以下错误:

common.c: In function ‘init_OpenSSL’:
common.c:12:5: warning: implicit declaration of function ‘THREAD_setup’
/tmp/ccvI3HX4.o: In function `handle_error':
common.c:(.text+0x3a): undefined reference to `ERR_print_errors_fp'
/tmp/ccvI3HX4.o: In function `init_OpenSSL':
common.c:(.text+0x51): undefined reference to `THREAD_setup'
common.c:(.text+0x5a): undefined reference to `SSL_library_init'
common.c:(.text+0x97): undefined reference to `SSL_load_error_strings'
/tmp/ccRA0Co9.o: In function `do_client_loop':
client.c:(.text+0x71): undefined reference to `BIO_write'
/tmp/ccRA0Co9.o: In function `main':
client.c:(.text+0xbb): undefined reference to `BIO_new_connect'
client.c:(.text+0x106): undefined reference to `BIO_ctrl'
client.c:(.text+0x18e): undefined reference to `BIO_free'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

显然,它无法链接到头文件...当我按照一个论坛的建议运行时,gcc -Wall common.c client.c -o client -lcrypto -lssl我得到了

common.c: In function ‘init_OpenSSL’:
common.c:12:5: warning: implicit declaration of function ‘THREAD_setup’
/tmp/cc2gjx8W.o: In function `init_OpenSSL':
common.c:(.text+0x51): undefined reference to `THREAD_setup'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

但是添加-lpthread并不能帮助解决问题...

知道为什么会这样以及如何解决吗?

我的猜测是lcrypto和lssl默认安装在ubuntu中,并且-lcypto告诉链接器查看系统头文件而不是openssl安装文件...

任何帮助或指针表示赞赏!

谢谢!

Jon*_*tez 5

在openssl书的某些代码版本中,与线程相关的功能存储在reentrant.c中(实际上,在我所看到的版本中有TRHEAD_setup的声明),因此请尝试:

gcc -Wall common.c client.c reentrant.c -o client -lcrypto -lssl
Run Code Online (Sandbox Code Playgroud)