Reputation: 11763
Now I am developing a C++ library, which is expect to have C interface. In order to do that I have two solutions:
Solution 1:
lib_c_header.h
lib_c_header_imp.cpp
Solution 2:
lib_c_header.h
lib_c_header_imp.c
Then the first question I have is : is it valid to have a C interface header and C++ implementation file as a wrapper of the C++ library?
Then move to the second solution, I will create a C interface header and C implementation file. In the C implementation file, C++ classes from the library will be invoked. However, when I do that, I always have cmath syntax errors:
c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\cmath(19): error C2061: syntax error : identifier 'acosf'
These errors lead me to the following codes in the cmath
file:
_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;
I think the problem comes from the fact that the implementation file lib_c_header_imp.c
will be compiled as C file while in the file some C++ classes will be invoked. I was wondering whether there is a solution to this problem. Thanks.
Upvotes: 0
Views: 1285
Reputation: 76346
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.
Upvotes: 3
Reputation:
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.
Upvotes: 0