如何用OpenSSL编译一个简单的程序?

时间:2011-06-10 08:52:25

标签: 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> 

我运行 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

显然它无法链接到头文件...... 当我按照一个论坛中的建议运行 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

但添加-lpthread无助于解决问题......

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

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

感谢任何帮助或指示!

谢谢!

1 个答案:

答案 0 :(得分:4)

在openssl book的一些代码版本中,与线程相关的函数存储在reentrant.c中(事实上,在我看过的版本中,TRHEAD_setup的声明就在那里),所以请尝试:

gcc -Wall common.c client.c reentrant.c -o client -lcrypto -lssl