suj*_*eet 5 c c++ complex-numbers complextype c++11
我需要将C库的头部包含在我的C++ 11代码中.现在,标题提供了涉及大量double complex所有地方的例程和数据结构.例如,
#include <complex.h>
//..
typedef struct parameters
{
// ...
double complex Vud;
} parameters;
// ...
double complex polylog(int n, int m, double x);
Run Code Online (Sandbox Code Playgroud)
我把这个文件带到我的C++ 11源代码中extern "C" { #include "include.h" }(这是实际的文件名,信不信由你).如果我添加了-std = c ++ 11,那么g ++(试过4.7.3和4.8.2)和clang(3.3)就会疯狂.
数百万行g ++错误包括:
include/g++-v4/cmath:98:3: error: template with C linkage
Run Code Online (Sandbox Code Playgroud)
并且clang给出:
cmath:84:3: error: declaration conflicts with target of using declaration already in scope
abs(double __x)
^
/usr/include/stdlib.h:773:12: note: target of using declaration
extern int abs (int __x) __THROW __attribute__ ((__const__)) __wur;
^
/usr/lib/gcc/x86_64-pc-linux-gnu/4.7.3/include/g++-v4/cstdlib:245:14: note: using declaration
using std::abs;
^
Run Code Online (Sandbox Code Playgroud)
我不知道如何解决这个问题.这样做的正确方法是什么?显然这些必须是可互操作的,但我不知道这个伎俩.
小智 7
在100%标准C++中,您只是简单地不能在extern "C"块中包含标准头.您需要修改include.h标头以使C++友好,首先包括其所需的标头extern "C",并在extern "C"块内声明自己的名称.
17.6.2.2标题[using.headers]
[...]
3翻译单位应仅在任何外部声明或定义之外包括一个标题,并应在该翻译单位的第一次参考之前以词汇方式包括标题,以及该标题中声明的任何实体.
干
extern "C" {
#include <complex.h>
}
Run Code Online (Sandbox Code Playgroud)
无效,因为标题随后包含在声明中.即使它只是间接包含的另一个标题,这也适用<complex.h>.
对于常见实现可能include.h有用的,如果修改是不切实际的,则首先手动包括include.h将包含自身的所有头.假设这些标题使用适当的保护来使第二个包含无操作,那么include.h包含它们的事实将不会导致任何错误.