滚龙

导航

#include预处理指令

预处理指令是由编译器的预处理阶段执行的命令,这个阶段在代码被编译成目标代码之前执行。

预处理指令都以#字符开头。

#include 指令用于包含其他的头文件

#include语句不能以分号结尾

 

例如:

#include <iostream>
#include <iostream.h>
#include "iostream.h"

 

上面三条语句的写法有着细微的差别,其含义也有所不同。

 

<iostream>是遵循C++标准的,表示你使用的是标准命名空间,所以必须同时在程序开始的地方对标准命名空间加以引用。

#include <iostream>
using namespace std;

 

<iostream.h>则没有遵循C++标准,而是延续了C语言的写法。

源自网络上的资料: 

 

其实并没有 <iostream.h> 这样的东西,标准化委员会在简化非C标准头文件时用 <iostream> 取代了它,但又没有完全取消 <iostream.h> 的使用,很多编译器都同时支持 <iostream>和<iostream.h>,造成现在的局面,标准化委员会确实有不得已的苦衷。

 

当年在标准化委员会动手重建新的标准库的时候,遇到了问题。为了避免类名和函数名的冲突问题,引入了名字空间std。但无数现有的C++代码都依赖于使用了多年的伪标准库中的功能,例如,声明在 <iostream.h> 和 <complex.h> 等头文件中的功能。现有软件没有针对使用名字空间而进行相应的设计或者升级,如果用std来包装标准库导致已有的代码不能使用。

 

因此,标准化委员会决定为包装了std的那部分标准库构建新的头文件名。将现有C++头文件名中的.h去掉,所以就出现了<iostream.h> 和<iostream>等很多双胞胎。对于C头文件,采用同样方法,但在每个名字前还要添加一个C,所以C的<string.h>变成了<cstring>。

 

旧的C++头文件是官方明确反对使用的,但旧的C头文件则没有(以保持对C的兼容性)。如果能明白字符串头文件的使用,举一反三,其他的也差不多会用了例如:

<string.h>是旧的C头文件,对应的是基于char*的字符串处理函数;

<string>是包装了std的C++头文件,对应的是新的strng类;

<cstring>是对应旧的C头文件的std版本。

 

如果编译器支持,那使用 #include <iostream>,得到的是置于名字空间std下的iostream库的元素;如果使用 #include <iostream.h>,得到的是置于全局空间下同样的元素。在全局空间获取元素会导致名字冲突,而设计名字空间的初衷正是用来避免这种名字冲突的发生,因此应尽量使用<iostream>。

在gcc的头文件iostream.h中,包含如下两行代码,说明了为什么在使用<iostream.h>的时候不需要using namespace std了。

#include <iostream>

using std::iostream;

 

而#include <> 和 #include “”之间的区别是,前者优先从编译选项指定的目录开始查找,如果找不到则从包含了该预处理语句的文件所在目录中查找;后者则正好相反。

源自MSDN的解释:

" " 
This   form   instructs   the   preprocessor   to   look   for   include   files   in   the   same   directory   of   the   file   that   contains   the   #include   statement,   and   then   in   the   directories   of   any   files   that   include   (#include)   that   file.   The   preprocessor   then   searches   along   the   path   specified   by   the   /I   compiler   option,   then   along   paths   specified   by   the   INCLUDE   environment   variable. 
<> 
This   form   instructs   the   preprocessor   to   search   for   include   files   first   along   the   path   specified   by   the   /I   compiler   option,   then,   when   compiling   from   the   command   line,   along   the   path   specified   by   the   INCLUDE   environment   variable.

posted on 2010-12-07 21:31  滚龙  阅读(1011)  评论(0编辑  收藏  举报