C和C++混合编程问题
分析以下一段代码: /*=======sum.h=========*/ #ifndef SUM_H #define SUM_H #include <stdio.h> int sum(int a,int b); #endif; /*=======sum.c=========*/ #include "sum.h" int sum(int a,int b) { int c=a+b; return c; } /*====main.cpp======*/ #include "sum.h" void mian(){ cout << sum(1,2)<<endl; } 调用以上三个文件,编译通过,但是执行是出现以下问题: obj : error LNK2001: 无法解析的外部符号 "int __cdecl sum(int,int)" (?sum@@YAHHH@Z) 问题出在哪里呢? 在main.cpp里调用了sum.c,也就是说在C++程序里调用了C程序,此时如果没有作相应处理将会出现链接错误。
那么如果在C中调用C++代码,以及如何在C++中调用C的代码呢? extern "C"表示编译生成的内部符号名使用C约定。 1. 如何在C++中调用C呢? C++调用C,extern "C" 的作用是:让C++连接器找调用函数的符号时采用C的方式 本文开头提出的笔试题可以这样修改: /*=======sum.h=========*/ #ifndef SUM_H #define SUM_H #include <stdio.h> int sum(int a,int b) { int c=a+b; return c; } /*====main.cpp======*/ extern "C" { #include "sum.h" } void mian(){ cout << sum(1,2)<<endl; } 执行成功 相信到这里差不多明白了 2. 怎样在C里调用C++呢? 在C中引用C++函数(C调用C++,使用extern "C"则是告诉编译器把cpp文件中extern "C"定义的函数依照C的方式来编译封装接口,当然接口函数里面的C++语法还是按C++方式编译) 执行:test1.obj : error LNK2019: 无法解析的外部符号 _sum,该符号在函数 _main 中被引用 /*=======sum.h=========*/ #ifndef SUM_H #define SUM_H #include <stdio.h> int sum(int a,int b); #endif; /*=======sum.cpp=========*/ #include "sum.h" extern "C" { int sum(int a,int b) { int c=a+b; return c; } } /*====main.c======*/ #include "sum.h" void mian(){ cout << sum(1,2)<<endl; } 3. 标准规范写法 一般我们都将函数声明放在头文件,当我们的函数有可能被C或C++使用时,我们无法确定被谁调用,使得不能确定是否要将函数声明在extern "C"里,所以,我们可以添加 #ifdef __cplusplus extern "C" { #endif //函数声明 #ifdef __cplusplus } #endif 利用以上声明形式就可以综合运用了。 /*=======sum.h=========*/ #ifndef SUM_H #define SUM_H #include <stdio.h> int sum(int a,int b); #endif; /*=======sum.cpp=========*/ #include "sum.h" int sum(int a,int b) { int c=a+b; return c; } /*====main.c======*/ #include "sum.h" void mian(){ cout << sum(1,2)<<endl; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |