extern "C(二)

2015-01-22 22:53:12 · 作者: · 浏览: 182
++ -o cppFile cppFile.cpp cExample.c编译器会报错;而当cppFile.cpp 文件中不使用下列语句
  extern "C"
  {
  #i nclude "cExample.h"
  }
  而改用
  #i nclude "cExample.h"
  extern "C" int add( int x, int y );
  时
  g++ -o cppFile cppFile.cpp cExample.c的编译过程会把add函数按c++的方式解释为_foo_int_int这样的符号。
  )
  如果C++调用一个C语言编写的.DLL时,当包括.DLL的头文件或声明接口函数时,应加extern "C" { }。
  (2)在C中引用C++语言中的函数和变量时,C++的头文件需添加extern "C",但是在
C语言
中不能直接引用声明了extern "C"的该头文件,应该仅将C文件中将C++中定义的extern "C"函数声明为extern类型。
  笔者编写的C引用C++函数例子工程中包含的三个文件的源代码如下:
  //C++头文件 cppExample.h
  #ifndef CPP_EXAMPLE_H
  #define CPP_EXAMPLE_H
  extern "C" int add( int x, int y );
  #endif
  //C++实现文件 cppExample.cpp
  #i nclude "cppExample.h"
  int add( int x, int y )
  { ?www.2cto.com
  return x + y;
  }
  /* C实现文件 cFile.c
  /* 这样会编译出错:#i nclude "cppExample.h" */
  extern int add( int x, int y );
  int main( int argc, char* argv[] )
  {
  add( 2, 3 );
  return 0;
  }