【发布时间】:2017-09-04 12:26:42
【问题描述】:
我有一个 C++ 库,它公开了一些 API(通过 cppH.h),它是一个静态库 (*.lib)。 我想在 C 代码中使用它,因此编写了一个 C Wrapper,如下所示。但是,我收到如下构建错误。请在这方面帮助我知道我错过了什么。我来自here
cppH.h - C++ 库的头文件
class Abc
{
int ma, mb;
public:
void pass(int a,int b);
int sum();
};
CWrapper.h
#ifdef __cplusplus
extern "C" {
#endif
typedef struct Abc_C Abc_C;
Abc_C* New_Abc();
void pass_in_C(Abc_C* cobj, int a, int b);
int sum_in_C(Abc_C* cobj);
#ifdef __cplusplus
}
#endif
CWrapper.cpp
#include "CWrapper.h"
#include "cppH.h"
extern "C" {
Abc_C* New_Abc()
{
return new Abc_C();
}
void pass_in_C(Abc_C* cobj, int a, int b)
{
cobj->pass(a, b);
}
int sum_in_C(Abc_C* cobj)
{
cobj->sum();
}
}
CWrapper.cpp & CWrapper.h 静态链接到 C++ 库 cppH.lib & cppH.h.
编译错误:
1>------ Rebuild All started: Project: CApp, Configuration: Debug Win32 ------
1> CS.c
1> CWarpperS.cpp
1>c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwarppers.cpp(7): error C2512: 'Abc_C' : no appropriate default constructor available
1>c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwarppers.cpp(12): error C2027: use of undefined type 'Abc_C'
1> c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwrapper.h(6) : see declaration of 'Abc_C'
1>c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwarppers.cpp(12): error C2227: left of '->pass' must point to class/struct/union/generic type
1>c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwarppers.cpp(17): error C2027: use of undefined type 'Abc_C'
1> c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwrapper.h(6) : see declaration of 'Abc_C'
1>c:\users\user1\documents\ccg\vsprojects\expapp\capp\cwarppers.cpp(17): error C2227: left of '->sum' must point to class/struct/union/generic type
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
【问题讨论】:
-
编译器错误日志中的
cwarppers.cpp是什么?您没有显示这样的文件(尽管它似乎拼写错误)。 -
extern "C"并不意味着它是 C 代码,只是它使用 C ABI 和命名约定。函数体仍然是 C++。