关于linux:如何使用OpenSSL包括编译.c文件?

How to compile .c file with OpenSSL includes?

我正在尝试编译一个包含以下内容的小.c文件:

1
2
3
4
#include <openssl/ssl.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <openssl/evp.h>

在我拥有.c文件的同一文件夹中,我拥有带有所有这些文件(以及更多文件)的/ openssl,也在突触包管理器中,我看到安装了OpenSSL,我正在尝试使用以下方法进行编译:

1
gcc -o Opentest Opentest.c -lcrypto

但我总是得到错误:

1
2
3
4
error: openssl/ssl.h: No such file or directory
error: openssl/rsa.h: No such file or directory
error: openssl/x509.h: No such file or directory
error: openssl/evp.h: No such file or directory

我要编译的文件只是一个.c文件,没有Makefile或./configure。

我已经尝试过:

1
env CFLAGS=-I/path/to/openssl/

并尝试再次编译,但我得到相同的错误。

我应该怎么做才能用openssl include进行编译?


您的包含路径表明您应该针对系统的OpenSSL安装进行编译。您的软件包目录中不应包含.h文件-它应从/usr/include/openssl中拾取它们。

普通的OpenSSL软件包(libssl)不包含.h文件-您还需要安装开发软件包。在Debian,Ubuntu和类似发行版中,此名称为libssl-dev;在CentOS,Fedora,Red Hat和类似名称中,此名称为libssl-devel


使用-I标志正确地gcc。

gcc -I/path/to/openssl/ -o Opentest -lcrypto Opentest.c

-I应该指向包含openssl文件夹的目录。


使用下面的代码段作为所引用挑战的解决方案;

1
2
yum install openssl
yum install openssl-devel

经过测试并证明在带有keepalived版本1.2.7的CentOS版本5.4上有效。


您需要包括库路径(-L / usr / local / lib /)

gcc -o Opentest Opentest.c -L/usr/local/lib/ -lssl -lcrypto

这个对我有用。


从openssl.pc文件

1
2
3
4
5
6
7
8
9
10
11
12
prefix=/usr
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir=${prefix}/include

Name: OpenSSL
Description: Secure Sockets Layer and cryptography libraries and tools
Version: 0.9.8g
Requires:
Libs: -L${libdir} -lssl -lcrypto
Libs.private: -ldl -Wl,-Bsymbolic-functions -lz
Cflags: -I${includedir}

您可以从中记下Include目录路径和Libs路径。现在,包含文件的前缀为/home/username/Programming
因此,您的包含文件选项应为-I//home/username/Programming

(是的,我从上面的评论中得到了它)

这只是为了删除有关标头的日志。您也可以提供-L选项来与-lcrypto库链接。


如果OpenSSL标头位于当前目录的openssl子目录中,请使用:

1
gcc -I. -o Opentest Opentest.c -lcrypto

预处理程序希望通过-I选项中的" ."创建一个名称,例如" ./openssl/ssl.h",并在尖括号中指定该名称。如果您在双引号(#include"openssl/ssl.h")中指定了名称,则可能永远不需要问这个问题。 Unix上的编译器通常会自动在当前目录中搜索用双引号引起来的标头,但是对于在尖括号(#include )中引起的标头则不会这样做。它是实现定义的行为。

您没有说OpenSSL库在哪里-您可能需要添加适当的选项和参数来指定它,例如'-L /opt/openssl/lib'。


对于此gcc错误,您应参考有关搜索路径的gcc文档。

简而言之:

1)如果在#include中使用尖括号(<>),则gcc首先会从/ usr / local / include和/ usr / include等系统路径中搜索头文件。

2)-Ldir命令行选项指定的路径将在默认目录之前搜索。

3)如果您将带#include的quotation(")用作#include" file",则将首先搜索包含当前文件的目录。

因此,您的问题的答案如下:

1)如果要在源代码文件夹中使用头文件,请在#include指令中将<>替换为""。

2)如果要使用-I命令行选项,请将其添加到编译命令行中。(如果在环境变量中设置CFLAGS,则不会自动引用它)

3)关于包配置(openssl.pc),我认为在构建配置中未明确声明的情况下不会引用它。