---
title: "__cplusplus的用处 "
author: "sealbird"
date: "2010-12-29T14:07:20Z"
tags: ["Blog", "C", "C#", "C++", "HTML"]
categories: ["编程语言"]
slug: "cplusplus"
draft: false
lastmod: "2010-12-29T14:07:20Z"
id: 854814
url: "https://sealbird.iteye.com/blog/854814"
---

```c++
作者: Aprilgogo   发表日期: 2007-03-10 16:26   复制链接 





经常在/usr/include目录下看到这种字句：



Code:
#ifdef __cplusplus
extern "C" {
#endif
...
#ifdef __cplusplus
}
#endif

[ctrl+a select all]



不太明白是怎么用的。今天阅读autobook，在第53页看到了作者的解释：C/C++编译器对函数和变量名的命名方法不一样(例如C++中重载的函数有多个名字，而C的函数只有一个名字)，这样当C编译器去引用C++编译器编译出来的符号时，会找不到链接。因此，当一个头文件可能既被C程序引用，又被C++程序引用时，需要使用如上代码进行区分。

上面的写法太复杂了，况且两个大括号{和}分离，会造成有些编辑器的缩进错误。更好的手法是将如下代码定义在一个公共头文件中，然后所有其它头文件去引用它：



Code:
#ifdef __cplusplus
#  define BEGIN_C_DECLS         extern "C" {
#  define END_C_DECLS           }
#else
#  define BEGIN_C_DECLS
#  define END_C_DECLS
#endif

[ctrl+a select all]



有关__cplusplus和extern "C"的更多用法，可以参考下文：

《C++中extern “C”含义深层探索》
http://hi.baidu.com/17cpp/blog/item/a46bfd13a4816e025aaf53f6.html
```