c++ - C++11 中具有 C 链接的复杂类型

标签 c++ c c++11 complex-numbers complextype

我需要将 C 库的 header 包含到我的 C++11 代码中。现在, header 提供的例程和数据结构到处都涉及大量 double complex。例如,

#include <complex.h>
//..
typedef struct parameters
{
    // ...
    double complex Vud;
} parameters;
// ...
double complex polylog(int n, int m, double x);

我将这个文件放入我的 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

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;
             ^

我不确定如何解决这个问题。这样做的正确方法是什么?显然这些必须是可互操作的,但我不知道诀窍。

最佳答案

在 100% 标准的 C++ 中,你不能在 extern "C" 中包含标准头文件。堵塞。您需要修改您的 include.h header 对 C++ 友好,首先在 extern "C" 之外包含其所需的 header , 并在 extern "C" 中声明自己的名字 block 。

17.6.2.2 Headers [using.headers]

[...]

3 A translation unit shall include a header only outside of any external declaration or definition, and shall include the header lexically before the first reference in that translation unit to any of the entities declared in that header.

extern "C" {
#include <complex.h>
}

无效,因为 header 随后包含在声明中。即使它是另一个仅间接包含 <complex.h> 的 header ,这也适用。 .

作为修改 include.h 的解决方法,什么可能适用于常见的实现是不切实际的,首先手动包含 include.h 的所有 header 会包括自己。假设这些 header 使用适当的守卫使第二次包含成为空操作,include.h 的事实包含它们将不会导致任何错误。

关于c++ - C++11 中具有 C 链接的复杂类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22115996/

相关文章:

c - C getopt 和 getopt_long 是否仅适用于主要参数?

c - 如何对某个函数返回的最后一个节点执行操作?

c - 链表: Moving a node from one list to another

c++ - 在 C++ 中将具有 unique_ptr 的对象插入 vector

c++ - basic_string<CharT> 与 CharT*

c++ - std::unordered_map::insert 重载重载

c++ - 乘以小数不会给我一个小数答案来反馈给我的变量

c++ - Lua、线程和 C++ 异常

c++17 通过生成预先声明的类型列表的笛卡尔积来制作 std::variant

c++ - 强制 vector 的分配器指向特定位置