1、 如何判断一段程序是由 C 编译程序编译的还是由 C++编译程序编译的?
考查点:__cplusplus 用法、C 与 C++的混合编译
注释:
本来如同#ifdef XXXXX 这样的条件编译,需要人为定义一个匹配的宏,但是,在 c++编译
器中,已经内置了这个宏的定义,所以在使用 c++编译器编译其他语言(这里是 C 语言,
当然得编译器支持的语言哈)时,用上这样的方式,可以让编译器把 extern “C”代码块中的
内容按照 C 语言的编译方式进行编译。为什么要这样呢?因为 c++中支持函数重载,而 C
语言不支持,c++对函数经过了其他处理,如果不加 extern “C”限制按照 C 语言的方式编译,
那么 c++编译器在编译 C 语言函数时可能就会找不到链接路径而报错。
#include<stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
int a=10;
#ifdef __cplusplus
}
#endif
int main(void)
{
printf("%d",a);
return 0;
}
//用 gcc 编译后,C 语言编译器是没有__cplusplus 这个宏的
int a =10;
int main (void)
{
printf("%d", a);
return 0;
}
//用 g++编译后,C++语言编译器能够识别__cplusplus 这个宏
extern "C" {
int a =10;
}
int main (void)
{
printf("%d", a);
return 0;
}
#ifdef __cplusplus
printf(“c++”);
#else
printf(“c”);
#endif