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的出现就是为了混合编程。

你可能感兴趣的:(编程,c,语言)