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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值