#包括在功能体内部或降低其可见性

#include inside function body or reduce its visibility

本文关键字:可见性 内部 包括 功能      更新时间:2023-10-16

有没有办法缩小#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()
}

不可能将"includes"限制为using文件的子集。包含之后的任何内容都始终可见。

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

#include直接在该点插入文件内容。因此,这取决于标头的内容,但通常答案是否定的。如果它是一个C标头,围绕着包含一个命名空间,可能会起作用,但我不确定。

#include在编译过程中被解析,您不能在代码中更改它。但是您可以使用预处理器指令来控制包含哪些文件:

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

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

.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"
}