c++ - 将 C 库移植到 C++

标签 c++ c c++11

我想知道这是否是将 C 库移植到 C++ 的正确方法;在这个例子中,我编写了一个 2 行 C 头文件,其中包含一个函数和一个管理指针的 typedef

lib.h

#ifndef LIB_H
#define LIB_H

#include <math.h>

double foo(double a) { return (log(a)); }

typedef double (*PtoFoo)(double);

#endif // LIB_H

lib.hpp

#ifndef LIB_HPP
#define LIB_HPP

namespace lib {
extern "C" {
#include "lib.h"
}
}

#endif // LIB_HPP

以及在 C++11 中进行的一些测试

#include <iostream>
#include "lib.hpp"
#include <functional>

int main() {
  // call to the function
  std::cout << lib::foo(42354.343) << "\n";
  // trying the pointer to function type
  lib::PtoFoo ptr = lib::foo;
  std::function<double(double)> f(ptr);
  std::cout << f(342.4) << "\n";
  return (0);
}

现在我的注意力集中在指针、函数指针和函数上,但总的来说,我想知道这是否是将标准 C 代码移植到 C++ 并使用带有 namespace 的新 C++ 接口(interface),而不会出现适得其反的情况。

最佳答案

是的,这是正确的方法。

或者,您可以使用 __cplusplus 预处理器标记在同一头文件中定义 C++ 接口(interface):

#ifdef __cplusplus
namespace lib {
extern "C" {
#endif

typedef ...

#ifdef __cplusplus
}
}
#endif

这种方法的优点是只需要一个头文件。

关于c++ - 将 C 库移植到 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20551783/

相关文章:

c++ - 查找数组中的最小元素及其索引

c - 将二进制数拆分为数字

c++ - 使用 cin 读取带有任意空格的逗号分隔整数对 (x,y)

c++ - 为什么我需要传递一个比较器来构造一个 priority_queue,当它是 lambda 时,而不是当它是 std::greater 时?

c++ - 在鼠标悬停时更改图片框,并在鼠标离开时重置

c++ - 使用通用函数指针参数化函数模板的巧妙方法

c++ - 测试静态局部对象的初始化是否线程安全

c - 为什么“while(!feof(file))”总是错误的?

php - 如何为从php脚本调用的c程序设置计时器?

sockets - boost async_accept无法与boost asio use_future选项一起使用