C++中extern “C”含义深层探索

参考文章:http://www.cppblog.com/Macaulish/archive/2008/06/17/53689.html

跪求指出错误!

Why need it?

extern "C"的根本目的是为了实现C和C++的混合编程。

The principle

根本原因在于C++和C中的函数的编译方式不同。如函数void foo(int n);
  • 被C编译器编译后在符号表中的名字形如:_foo
  • 被C++编译器编译后在符号表中的名字形如:_foo_int
C++中为什么要采用这种编译方式呢?因为C++中支持函数重载,而C不支持函数重载,再回想一下函数重载的要求:函数名相同,函数参数类型不同,但是不能以返回值不同做为函数重载的条件。因为函数被C++编译器编译后在符号表中的名字由函数名、函数参数类型组成,不包括返回值类型,这就是函数重载的底层实现机制。
所以为了实现C和C++的混合编程,就引入了extern “C”。extern "C"是为了告诉编译器采用C的编译方式,只能在C++中使用。下面以具体实例来分析它的作用:
1. 在C中使用C++中的函数,key point:
  • C++头文件中的函数用extern "C"来标识,在C中extern外部调用C++中的函数,且只能使用这种方式,不能通过包含C++头文件的方式来调用,因为C中不能识别extern "C"符号
//C++ .h
#ifndef B_H
#define B_H
extern "C" void foo();
#endif

//.cpp
#include "B.h"
void foo(){}

//.c
//#include "B.h"  //error:因为C中不能识别extern "C"符号
extern void foo();
void main()
{
	foo();
}
  • CPP文件中的函数用extern "C"来标识,在C++头文件中外部引用这个函数,则在C中可以通过包含头文件的方式来调用C++中的函数
//C++ .h
#ifndef B_H
#define B_H
extern void foo();
#endif

//.cpp
extern "C" 
{
void foo(){}
}

//.c
#include "B.h" 
//extern void foo();  //两种方式都可以
void main()
{
	foo();
}


2. 在C++中使用C中的函数:
  • 在C的头文件中使用__cplusplus宏,C++中直接包含C头文件或外部引用来调用C中函数,不需要其它处理,C函数库中就是采用的这种方式
//C .h
#ifndef A_H
#define A_H

#ifdef __cplusplus
extern "C" {
#endif

	void foo();

#ifdef __cplusplus
}
#endif

#endif

//.c
#include "B.h"
void foo(){}

//.cpp
#include "B.h"
void foo();  //两种方式都可以
void main()
{
	foo();
}
  • C++中通过extern "C"来包含C头文件、直接外部引用两种方式来调用C中的函数
//C .h
#ifndef B_H
#define B_H
void foo();
#endif

//.c
#include "B.h"
void foo(){}

//.cpp
extern "C"
{
     #include "B.h"
}
//extern "C" void foo();  //两种方式都可以
void main()
{
	foo();
}



posted @ 2012-05-12 14:08  刘军newhand_liu  阅读(242)  评论(0编辑  收藏  举报