如果编译器在编译cpp文件,那么_Cplusplus就会被定义,如果是一个c文件在被编译,那么_STDC_就会被定义。_STDC_是预定义宏,当它被定义后,编译器将按照ANSIC标准来编译C语言程序。 所以,可以采用如下程序示例判断。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include<stdio.h>
#ifdef_cplusplus
#define USING_C 0
#else
#define USING_C 1
#endif
#include <stdio.h>
int main()
{
	if(USING_C)
		printf("C\n”);
	else
		printf("C++\n");
	return 0;
}

编写C与C++兼容的代码所需的宏如下:

1
2
3
4
5
6
7
#ifdef_cplusplus
extern "C" {
#endif
//具体的代码
#ifdef_cplusplus
}
#endif

在上例中,_cplusplus是cpp中的自定义宏,当定义了这个宏时,其表示这是一段cpp的 代码。也就是说,上面代码的含义为如果这是一段cpp的代码,那么加入extern “C"和}处理其中的代码。