extern "C"

 
 
首先,__cplusplus是cpp中的自定义宏,定义这个宏的话表示这是一段cpp的代码。

举个在cpp程序中常见的代码:
#ifdef __cplusplus
extern "C " {
#endif
…………
…………
#ifdef __cplusplus
}
#endif

上面代码的意思:如果编译器在编译cpp文件,那么__cplusplus宏就会被定义;如果是一个c文件在被编译那么__STDC__宏就会被定义。
如果整个程序是用C++写的,那么在C++里面写C要加上extern "C " {}进行说明。至于extern "C"这个指示编译器生成符号表时不改变标识符的名字。
实验:
test.h
#ifndef __TEST_H__
#define __TEST_H__

#ifdef __cplusplus
#include <iostream>
using namespace std;
extern "C"
{
#endif

void mytest();

#ifdef __cplusplus	
}
#endif

#endif

test.c/test.cpp

#include "test.h"
 void mytest()
 {
 	#ifdef __cplusplus
 	cout << "cout mytest extern ok" << endl;
 	#else
 	printf("printf mytest extern ok");
 	#endif
 }
main.c
#include <iostream.h>
#include "test.h"
int main(int argc, char *argv[])
{
	//cout<<"Hello C-Free!"<<endl;
	mytest();
	return 0;
}

当test源文件为:test.cpp测试结果为:

cout mytest extern ok

当test源文件为:test.c测试结果为:

printf mytest extern ok


猜你喜欢

转载自blog.csdn.net/graduation201209/article/details/79299671