C和C++混合编程问题

2020-01-06 13:47:28王振洲

 
  1. /*=======sum.h=========*/   
  2. #ifndef SUM_H  #define SUM_H 
  3. #include <stdio.h>   
  4. int sum(int a,int b);   
  5.   #endif; 
  6.   /*=======sum.cpp=========*/ 
  7.   #include "sum.h" 
  8.    
  9. extern "C"  { 
  10. int sum(int a,int b)  { 
  11. int c=a+b;  return c; 
  12. }  } 
  13.   /*====main.c======*/ 
  14.   #include "sum.h" 
  15.   void mian(){ 
  16.   cout << sum(1,2)<<endl; 
  17.   } 

3. 标准规范写法

一般我们都将函数声明放在头文件,当我们的函数有可能被C或C++使用时,我们无法确定被谁调用,使得不能确定是否要将函数声明在extern "C"里,所以,我们可以添加

 

 
  1. #ifdef __cplusplus   
  2. extern "C"   
  3. {   
  4. #endif   
  5. //函数声明   
  6. #ifdef __cplusplus   
  7. }   
  8. #endif