我有一系列使用C接口存储在库中的C++类(请参见下面的示例)。我有一个C程序,通过C接口包含这个C++库。这似乎工作得很好,直到我试图在new
和delete
的库中创建一个类。从C程序调用C++库中的新增和删除
我使用gcc编译C++库的C代码和g ++,我在unbunu上用Eclipse编写了项目。
,我得到的错误信息是
undefined reference to 'operator new(unsigned int)'
undefined reference to 'operator delete(void*)'
Libary .h文件
#ifndef CFOO_H_
#define CFOO_H_
#ifdef __cplusplus
class CBar {
public:
int i ;
};
class CFoo {
public:
int work();
};
extern CFoo g_foo ;
extern "C" {
#endif /* __cplusplus */
int foo_bar() ;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CFOO_H_ */
Libary CPP文件
#include "CFoo.h"
CFoo g_foo ;
int CFoo::work() {
CBar * b = new CBar();
delete b;
return 1;
}
int foo_bar() {
return g_foo.work();
}
主要的C文件
void * __gxx_personality_v0 ;
int main(void) {
printf("foo_bar 10 =%d\n", foo_bar()) ;
return 0;
}
我已经尝试了一些成功的东西,任何想法?
编辑
它看起来像是由Eclipse生成的自动生成的make文件的问题。一旦我手动改变了C applcations makefile与g ++而不是gcc链接,我就能够构建应用程序。请参阅下面的评论以获取更多信
这是一个链接问题,而不是代码问题。你能给我们提供关于你如何链接你的代码的信息吗? – Jerome 2011-05-03 18:17:30
它不在C++运行库中链接。你应该使用“g ++”作为链接命令,而不是“gcc”。 – 2011-05-03 18:19:08
如果程序中有任何C++代码,则包含'main'的翻译单元应该被编译为C++代码,而不是C代码。 – aschepler 2011-05-03 18:23:41