我目前正在尝试将一个大的C++程序链接到一个C“包装器”,以便与另一种语言的程序集成,该语言的编译器可以理解C但不了解C++(确切地说是Haskell GHC)。但是,我使用GHC或GCC尝试这样做时,遇到了奇怪的问题。
简洁地说,为了模拟这种情况,假设我有一个C文件作为主程序:
cmain.c
这段代码可以很好地编译。但是,如果 cppmodule.cpp 引用了另一个 .cpp 文件,代码会变成这样:
任何见解都将不胜感激。
简洁地说,为了模拟这种情况,假设我有一个C文件作为主程序:
cmain.c
#include "header.h"
#include <stdio.h>
int main () {
printf("%d\n", cppfun(12));
return 0;
}
同时在一个.cpp文件中定义了一个帮助函数:
cppmodule.cpp
#include "header.h"
#include "further.h"
class foobar {
public:
int getfive () {return 5;}
};
extern "C" {
int cppfun(int foo) {
foobar fb;
return fb.getfive();
}
}
这段代码可以很好地编译。但是,如果 cppmodule.cpp 引用了另一个 .cpp 文件,代码会变成这样:
cppmodule.cpp mk II
#include "header.h"
#include "further.h"
class foobar {
public:
int getfive () {return 5;}
};
extern "C" {
int cppfun(int foo) {
foobar fb;
return fb.getfive() + morecpp();
}
}
新的.cpp文件的位置类似于这样;
morecpp.cpp
#include "further.h"
class moreobjects {
public:
int getsix() {return 6;}
};
#ifdef __cplusplus
extern "C" {
#endif
int morecpp() {
moreobjects mo;
return mo.getsix();
}
#ifdef __cplusplus
}
#endif
在使用类似“gcc cmain.o cppmodule.o morecpp.o”这样的命令编译时,我突然遇到了错误;虽然使用g++编译可以解决问题,但正如我之前提到的,这种解决方案并不符合我的目的。
我在尝试编译这个示例时遇到的错误是:
max@SoutheastCorner:~/Projectsync/maketest$ gcc cmain.o cppmodule.o morecpp.o
cppmodule.o:(.eh_frame+0x4b): undefined reference to `__gxx_personality_v0'
collect2: error: ld returned 1 exit status
对于我的实际项目代码,尝试相同的操作会产生大量形式的错误信息:
hopnode.cpp:(.text._ZN9__gnu_cxx13new_allocatorISt10_List_nodeI4nodeIPcS3_EEE8allocateEmPKv[_ZN9__gnu_cxx13new_allocatorISt10_List_nodeI4nodeIPcS3_EEE8allocateEmPKv]+0x4d): undefined reference to `operator new(unsigned long)'
/tmp/ccaoEEFM.o: In function `__gnu_cxx::new_allocator<std::_Rb_tree_node<std::pair<char* const, node<char*, char*> > > >::allocate(unsigned long, void const*)':
hopnode.cpp:(.text._ZN9__gnu_cxx13new_allocatorISt13_Rb_tree_nodeISt4pairIKPc4nodeIS3_S3_EEEE8allocateEmPKv[_ZN9__gnu_cxx13new_allocatorISt13_Rb_tree_nodeISt4pairIKPc4nodeIS3_S3_EEEE8allocateEmPKv]+0x2c): undefined reference to `std::__throw_bad_alloc()'
hopnode.cpp:(.text._ZN9__gnu_cxx13new_allocatorISt13_Rb_tree_nodeISt4pairIKPc4nodeIS3_S3_EEEE8allocateEmPKv[_ZN9__gnu_cxx13new_allocatorISt13_Rb_tree_nodeISt4pairIKPc4nodeIS3_S3_EEEE8allocateEmPKv]+0x46): undefined reference to `operator new(unsigned long)'
任何见解都将不胜感激。
-lstdc++
。 - Oliver Charlesworth