我想知道这是否是将 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/