![](/img/trans.png)
[英]how do I include header files like list.h, queue.h and vector.h in C++ file?
[英]C++: How to include Paillier.h in a header file
我有一个C ++类key_gen ,其中包含一些类型为paillier_ prvkey_t的数据成员。 问题是我无法在标头文件key_gen.h中包含paillier库(用c 编写) 。 但我可以使用将其包含在我的key_gen.cpp中
extern "C"{
#include<paillier.h>
}
我正在使用cygwin运行我的代码,并且使用如下命令行:
g++ Key_Gen.cpp -L/cygdrive/c/cygwin/home/Win7/libpaillier -l:libpaillier.a -
-lgmpxx -lgmp
当我运行代码时,将paillier标头包含在我的头文件cygwin警报中。
该错误包含许多行,例如:
In file included from Key_Gen.h:13:0,
from Key_Gen.cpp:2:
/usr/local/include/paillier.h:63:3: note: previous declaration as ‘typedef
struct paillier_pubkey_t paillier_pubky_t’} paillier_pubkey_t;
^
有人可以告诉我如何解决问题吗?
当您告诉C或C ++编译器处理文件foo.cpp
,编译的第一阶段是预处理,该过程扩展宏,替代定义并扩展诸如#include
预处理器指令。
在早期,预处理器是一个单独的程序,它动态生成输出:C编译器本身并不了解#include
,而看到的只是一条代码流。
今天,预处理器通常是编译器(gcc,MSVC等)不可或缺的一部分,但是您在命令行上指定的每个源文件的单流效果仍然相同,并且您仍然可以访问编译器以生成输出作为单个中间文件进行预处理,以便您可以查看正在进行的翻译(gcc / g ++的-E选项)。 因此,如果您写:
// Foo.h
int foo;
// Bar.cpp
#include "Foo.h"
int bar;
#include "Foo.h"
编译器看到的是单个连续流:
/* "Bar.cpp" from command line */
// Bar.cpp
/* "Foo.h" from Bar.cpp:2 */
int foo;
/* end "Foo.h" */
int bar;
/* "Foo.h" from Bar.cpp:4 */
int foo;
/* end "Foo.h" */
/* end "Bar.cpp" */
#include
, #include
进行重复数据删除,因此多个include会产生重复数据。 如果要将paillier.h
添加到自己的.h
文件中,则需要防止此重复。 有两种常见的方法可以做到这一点。
在.h文件的开头,使用预处理程序指令#pragma,GNU C和C ++编译器都可以理解:
#pragma once
优点:预处理程序在#include
语句中检测到重复项,因此不必重新读取文件。 缺点:大多数编译器使用包含文件的路径来执行此操作,因此
#include "../include/foo.h"
#include "foo.h"
可能都引用同一文件,但在某些编译器上仍会产生重复。
在.h文件的开头,检查唯一预处理器符号的定义,如果未定义,请对其进行定义
#ifndef PAILLIER_H
#define PAILLIER_H
在文件的最后
#endif // PAILLIER_H (comment is optional)
优点:重复数据消除,与路径无关。 缺点:如果您的监护人名称不够唯一,可能会引起问题(我在一个项目中有人在多个头文件中使用“ HEADER”)。缺点:预处理程序仍必须读取整个头文件才能找到#万一。
综上所述
您可能还想添加以下内容,以使文件在同时包含C和C ++时起作用
#ifdef __cplusplus
extern "C" {
#endif
// all your symbols etc here
#ifdef __cplusplus
}; // extern "C"
#endif
这将使您的头文件看起来像这样:
#ifndef PAILLIER_H
#define PAILLIER_H
#ifdef __cplusplus
extern "C" {
#endif
// original code here
...
// end original code
#ifdef __cplusplus
}; // extern "C"
#endif
#endif // PAILLIER_H
要么
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
// original code here
...
// end original code
#ifdef __cplusplus
}; // extern "C"
#endif
-编辑-
没有理由不能同时使用两者
#pragma once
#ifndef MYPROJECT_SOMETHING_H
...
#endif
这样,如果#pragma由于路径原因使您失败,那么您仍然会受到保护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.