在 c++ 中新建和删除从 C 程序调用库
我有一系列 C++ 类存储在带有 C 接口的库中(请参见下面的示例)。我有一个 C 程序,通过 C 接口包含这个 C++ 库。这似乎工作得很好,直到我尝试使用 new
和 delete
在库中创建一个类。
我使用 gcc 编译 C 代码,使用 g++ 编译 C++ 库,我在 unbunu 上使用 Eclipse 打包项目。
我收到的错误消息是
undefined reference to 'operator new(unsigned int)'
undefined reference to 'operator delete(void*)'
Libary H file
#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 file
#include "CFoo.h"
CFoo g_foo ;
int CFoo::work() {
CBar * b = new CBar();
delete b;
return 1;
}
int foo_bar( ) {
return g_foo.work( );
}
Main c file
void * __gxx_personality_v0 ;
int main(void) {
printf( "foo_bar 10 =%d\n", foo_bar() ) ;
return 0;
}
我尝试了一些方法但没有成功,有什么想法吗?
编辑
看起来这是由 Eclipse 生成的自动生成的 make 文件的问题。一旦我手动更改 C 应用程序 makefile 以与 g++ 而不是 gcc 链接,我就能够构建应用程序。请参阅下面的评论以获取更多信息。
I have a series of c++ classes stored in a library with a C interface (see example below). And I have a C program that includes this c++ libary via the C interface. This seems to work well until I tried to create a class in the libary with new
and delete
.
I am using gcc to compile the C code and g++ for the C++ libary, I crated the projects with Eclipse on unbunu.
The error message that I get is
undefined reference to 'operator new(unsigned int)'
undefined reference to 'operator delete(void*)'
Libary H file
#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 file
#include "CFoo.h"
CFoo g_foo ;
int CFoo::work() {
CBar * b = new CBar();
delete b;
return 1;
}
int foo_bar( ) {
return g_foo.work( );
}
Main c file
void * __gxx_personality_v0 ;
int main(void) {
printf( "foo_bar 10 =%d\n", foo_bar() ) ;
return 0;
}
I have tried a few things with out success, any thoughts?
Edit
It looks like it was a problem with the auto generated make files produced by Eclipse. Once I manualy changed the C applcations makefile to link with g++ instead of gcc I was able to build the applcation. See comments below for more information.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
引用 unpersons:它不在 C++ 运行时中链接。您应该使用“g++”作为链接命令,而不是“gcc”。
Quoting unapersson: It's not linking in the C++ runtime. You should use "g++" as the link command, rather than "gcc".