读书人

C调用C++的函数出错了求解?解决方案

发布时间: 2012-04-19 14:36:43 作者: rapoo

C调用C++的函数出错了,求解?
一个头cpphead.h,c++ 实现文件:cppimpl.cpp, c调用文件 test.c
最后gcc test.c,这都是网上的,怎么我操作神了。

[root@put1 testc]# cat cpphead.h
#ifndef __CPPECAIYING
#define __CPPECAIYING
extern "C" int add(int x, int y);
#endif
[root@put1 testc]# cat cppimpl.cpp
#include<cpphead.h>

int add(int x, int y) {
return x + y;
}
[root@put1 testc]# cat test.c
#include "stdio.h"
extern int add(int x, int y);

int main(int argc, char* argv[]) {
add(3, 6);
//printf("result: %d\n", add(1, 20));
return 0;
}
[root@put1 testc]# gcc test.c
/tmp/ccqefKA2.o: In function `main':
test.c: (.text+0x1a): undefined reference to `add'
collect2: ld 返回 1
[root@put1 testc]#



[解决办法]
改成.c啊,gcc编译.c的,g++是编译.cpp的
[解决办法]
似乎你无法使用.o来实现这个目标,因为C++的.o和C的.o内部不是很兼容,如果你要混合编程,恐怕要把c++的做成一个库,然后链接进来。

个人还是认为实现部分也需要extern "C",楼上说不需要的知道extern "C"是干嘛的么?它修改了函数的在编译后.o中的符号修饰名,如果实现处不加extern "C",链接时还是会说找不到的。

至于personality错误,据说只有用-lstdc++才能实现,也就是你需要连接标准C++库才行,这样你得C/C++所有全混在一起了,最后就是一个乱。如果你为了试验混合编程,实际上这只是伪混合而已。

读书人网 >C语言

热点推荐