编写一个程序区分是C源代码还是C++源代码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ASJBFJSB/article/details/83650514

C++是在C语言的基础上建立的,所以在C++程序中沿用了很多C语言的东西,如printf函数既可以在C程序中使用,也可以在C++程序中使用,只需要引入相关的库文件即可。

如何区分是.c文件还是.cpp文件?

test.cpp
#include<cstdio>
int main(void){
	printf("hello world");
	return 0;
}

test.c
#include<stdio.h>
int main(void){
	printf("hello world");
	return 0;
}

上边test.c和test.cpp源文件如果使用g++进行编译,g++会把.c文件当作.cpp文件进行处理,这样是区分不出来的。实际上C++编译器在编译C++程序中会向文件中添加__cpluscplus宏,我们可以利用这个宏来区分当前源文件是C++程序还是C程序。

#include<stdio.h>
int main(void){
#ifdef __cpluscplus
	printf("c++\n");
#else
	printf("c\n");
#endif
	return 0;
}

此外,实际上我们在看C库的一些源码时,也会如上边的宏定义,因为C库函数完可能被C++程序使用,但是两者生成符号的规则却完全不相同。为了使得生成符号一致,需要加入extern “C”{}。
来自cstdio的一段源码就是用到了__cplusplus宏:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ASJBFJSB/article/details/83650514