#include函数体内部或降低其可见性

时间:2015-03-05 09:57:01

标签: c++

有没有办法缩小#include指令的范围?

我的意思是举例来做这样的事情

void functionOneDirective()
{
    #include "firstInstructionSet.h"
    registerObject();

    // cannot access instantiate()
}

void functionSecondDirective()
{
    #include "secondInstructionSet.h"
    instantiate();

    // cannot access registerObject()
}

void main()
{
    //cannot access instantiate() && registerObject()
}

4 个答案:

答案 0 :(得分:2)

不可能限制"包括"到使用文件的子集。对于包含后的任何内容,它始终可见。

如果您有兴趣提供"不同的"对某些功能的观点,考虑使用不同的名称空间来表达这些不同的观点"。

答案 1 :(得分:1)

#include直接在现场插入文件内容。所以这取决于标题的内容,但通常答案是否定的。如果它是围绕包含命名空间的C头可能有效,但我不确定。

答案 2 :(得分:1)

编译过程中

#include已解决,您无法在代码中更改它。但您可以使用预处理程序指令来控制包含哪些文件:

#if defined(A) && A > 3
#include 'somefile.h'
#else
#include 'someotherfile.h'
#endif

答案 3 :(得分:1)

您的问题的可能解决方案(以及组织源代码的正确方法)是为每个功能或相关功能组创建单独的.c文件。对于每个.c文件,您还要编写一个.h文件,其中包含该文件发布的.c文件中元素(类型,常量,变量,函数)的声明。 / p>

.h文件中声明的变量需要以extern关键字为前缀(让编译器知道它们位于不同的.c文件中)。

然后,让每个.c文件仅包含它需要的.h个文件(声明此.c文件中使用的函数/类型/变量的文件)。

实施例

档案firstInstructionSet.h

typedef int number;

void registerObject();

档案firstInstructionSet.c

void registerObject()
{
   /* code to register the object here */
}

档案oneDirective.h

void functionOneDirective();

档案oneDirective.c

#include "firstInstructionSet.h"

void functionOneDirective()
{
    registerObject();

    // cannot access instantiate() because
    // the symbol 'instantiate' is not known in this file
}

档案secondDirective.h

extern int secondVar;

void functionSecondDirective();

档案secondDirective.c

#include "secondInstructionSet.h"

int secondVar = 0;

void functionSecondDirective()
{
    instantiate();

    // cannot access registerObject() because
    // the symbol 'registerObject' is not known in this file
}

档案secondInstructionSet.h

void instantiate();

档案secondInstructionSet.c

void instantiate()
{
    /* code to instantiate here */
}

档案main.c

#include "oneDirective.h"
#include "secondDirective.h"

void main()
{
    // cannot access instantiate() && registerObject()
    // because these symbols are not known in this file.

    // but can access functionOneDirective() and functionSecondDirective()
    // because the files that declare them are included (i.e. these
    // symbols are known at this point
    // it also can access variable "secondVar" and type "number"
}