2017-09-01 87 views
2

所以我只是想知道,如果你#include something在例如header.h文件:如果您在.h文件中包含某些内容您是否必须再次包含相同的内容?

例如,这被称为header.h

#include <vector> 
#include <iostream> 
#include <somethingElse> 

所以,如果比如我做一个名为something.cpp我需要把所有这些包括陈述再次?

#include "header.h" 
// If I include #header.h in this file. Do the #include carry over to this file. Or do they not 

我想知道,因为每当我有<vector>东西在我的.h文件,我在.h文件以前使用的#include语句总是变成灰色,这意味着它们不使用。是因为我在.h文件中使用了它吗?它不是一个问题或任何我只是好奇。

+0

当您包含一个文件时,它基本上与复制文件内容而不是'#include'行一样。这与头文件中的#include行一样,就像其他任何东西一样。因此,如果头文件包含'',将其重新包含在文件中是多余的。 – Barmar

+0

所有的标准头文件都被设计成包含额外的次数没有效果,这就是为什么IDE显示它没有被使用。 – Barmar

+0

我想这个其他问题和答案解决这个https://stackoverflow.com/questions/6963143/headers-include-in-multiple-c-files(至少对于C) – Digits

回答

3

你不要需要包含这些头了,因为编译器能够找到这些头,你可以尝试阅读和理解makefile (or CMakeList) ,这将有助于

2

尝试总是避免通过“多文件包含”使用inclusion guard#pragma once以防止包含多个文件。

包含文件意味着文件的内容将被添加到您写的地方。

下面是一个例子:

// header.h 
const int vlaue = 10; 
const int value2 = 0; 

// main.cpp 

#include "header.h" 
#include "header.h" 

以上的 “header.h” 的内容被添加两次的main.cpp。

你知道结果是什么吗?这是编译时错误,抱怨重新定义了valuevalue2

在上面的例子中,我认为绿色程序员不会被它困住,但它只是一个解释,所以我说的是当一个巨大的程序中有许多头文件和许多源文件以及一些文件包含其他文件跟踪正确的文件包含会非常困难。

是解决方法使用inclusion guardspragma once例如:

让我们修改我们的header.h的样子:

// header.h 

#ifndef MY_HEADER_H 
#define MY_HEADER_H 

const int vlaue = 10; 
const int value2 = 0; 

#endif 

现在main.cpp中:

#include "header.h" 
#include "header.h" 
#include "header.h" 

上面的代码工作正常,没有重复的头文件内容被添加到main.cpp。你知道为什么吗?这是Macro的魔力。所以第一次预处理器检查一个宏是否已经被定义为MY_HEADER_H或者没有定义,并且第一次肯定它没有被定义,因此内容被添加。第二个等条件失败,因为宏已经定义,因此header.h的内容不会被添加到它被调用的地方。

包含警卫的缺点是,如果你有一个与包含警卫同名的宏,因此它已经被定义,所以内容永远不会被添加(空内容)。因此,你会得到一个编译时错误:

value, `value2` undeclared identifiers. 

第二个解决方案是使用pragma如:

让我们修改我们的header.h文件:

// header.h 
#pragma once 

const int vlaue = 10; 
const int value2 = 0; 

// main.cpp 

#include "header.h" 
#include "header.h" 

上面的代码工作正常所以没这是因为pragma once的魔力:这是一个非标准但广泛支持的预处理器指令,旨在使当前源文件在一次编译中只包含一次。因此,#pragma曾经具有与包括守卫一样的用途,但有几个优点,包括:更少的代码,避免名称冲突,并且有时可以提高编译速度。

  • 最后,你应该包括头无论其内容用于例如:

    // Shape.h 
    
    class Shape{ 
        // some code here 
    }; 
    
    // Cube.h 
    
    #include "Shape.h" 
    
    class Cube : public Shape{ 
        // some code here 
    }; 
    
    // Cuboid.h 
    
    // #include "Shape.h" 
    #include "Cube.h" // So here the Shape.h is added to Cube.h and Cube.h is added here. 
    
    class Cuboid : public Cube{ 
        // some code here 
    }; 
    
  • 正如你可以看到Shape.h的内容上方加入到间接Cuboid.h,因为它被添加到Cube.h和cuboid.h包含Cube.h,所以它被添加到它。因此,如果在一个源文件中包含两个头文件,那么如果没有包含保护或编译指令,那么您会在那里获得重复的内容。

相关问题