0

现在我正在开发一个 C++ 库,它应该有 C 接口。为此,我有两个解决方案:

解决方案1:

lib_c_header.h
lib_c_header_imp.cpp

解决方案2:

lib_c_header.h
  lib_c_header_imp.c

那么我的第一个问题是:将 C 接口头和 C++ 实现文件作为 C++ 库的包装器是否有效?

然后转到第二个解决方案,我将创建一个 C 接口头和 C 实现文件。在 C 实现文件中,将调用库中的 C++ 类。但是,当我这样做时,我总是遇到 cmath 语法错误:

c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\cmath(19): error C2061: syntax error : identifier 'acosf'

这些错误导致我在cmath文件中找到以下代码:

_STD_BEGIN
using _CSTD acosf; using _CSTD asinf;
using _CSTD atanf; using _CSTD atan2f; using _CSTD ceilf;
using _CSTD cosf; using _CSTD coshf; using _CSTD expf;
using _CSTD fabsf; using _CSTD floorf; using _CSTD fmodf;
using _CSTD frexpf; using _CSTD ldexpf; using _CSTD logf;
using _CSTD log10f; using _CSTD modff; using _CSTD powf;
using _CSTD sinf; using _CSTD sinhf; using _CSTD sqrtf;
using _CSTD tanf; using _CSTD tanhf; 

我认为问题在于实现文件lib_c_header_imp.c将被编译为 C 文件,而在文件中将调用一些 C++ 类。我想知道这个问题是否有解决方案。谢谢。

4

2 回答 2

3

The only way to write a C function that calls C++ is to compile it in C++ in an extern "C" block. Because the body of the function still has to be C++. So you'll have to have lib_c_header_imp.cpp.

You may either have separate header for the C wrapper and the full C++ interface or you may have them together in one header with the C++ part guarded by #ifdef __cplusplus. Depends on how big it is and how it will be most often used etc.

In the header you may only include C headers (i.e. <math.h> rather than <cmath>) or you may include C++ headers under #ifdef __cplusplus, but than you obviously can't use their content in the C wrapper part.

于 2013-08-07T08:58:31.600 回答
0

Generally you can include C in C++, i.e. use a C++ compiler when compiling the source. However, you can not use a C compiler to compile C++ code.

于 2013-08-07T08:58:23.573 回答