extern "C"

1:

cppExample.h

  #ifndef CPP_EXAMPLE_H
  #define CPP_EXAMPLE_H
  extern "C" int add( int x, int y );
  #endif

 

 

cppExample.cpp
  #i nclude "cppExample.h"
  int add( int x, int y )
  {
  return x + y;
  }

cFile.c 在C中引用C++语言中的函数和变量时,C++的头文件需添加extern "C",但是在C语言中不能直接引用声明了extern "C"的该头文件,应该仅将C文件中将C++中定义的extern "C"函数声明为extern类型。

        /* 这样会编译出错:#include "cppExample.h" */

  extern int add( int x, int y );
  int main( int argc, char* argv[] )
  {
  add( 2, 3 );
  return 0;

  }

 

 

2:

在C++中引用C语言中的函数和变量

cExample.h

  #ifndef C_EXAMPLE_H

  #define C_EXAMPLE_H

  extern int add(int x,int y);

  #endif

 

cExample.c

  #i nclude "cExample.h"

  int add( int x, int y )

  {

  return x + y;

  }

cppFile.cpp

  extern "C"

  {

  #i nclude "cExample.h"

  }

  int main(int argc, char* argv[])

  {

  add(2,3);

  return 0;

  }

结论: c调用c++的显然是不能#include a.h的, 但是c++调用c的是可以#include a.h但是要加上标示extern "C". extern的出现就是为了混合编程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值