#包括在功能体内部或降低其可见性
#include inside function body or reduce its visibility
有没有办法缩小#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"
}
相关文章:
- 如何更改唯一指针向量的可见性
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 限制静态库中符号的可见性 (MSVC/Visual C++)
- 班级成员可见性C++
- 内联模板函数的可见性
- Clang 是否可以在使用可见性属性时生成导入库(不带 __declspec(dllexport))?
- std::mutex 的发布-获取可见性保证是否仅适用于关键部分?
- 符号可见性和 gcc 警告
- C++/libscreen 无法更新可见性
- 在 C++11 线程中,std::mutex 对内存可见性有什么保证?
- C++继承构造函数的可见性
- CRTP - 嵌套叶类类型的可见性
- C++模板 - 实例之间的通用操作和成员可见性
- 放松的订单和线程间可见性
- GCC 6.x警告有关Lambda可见性
- C++ 中的Shared_ptr和内存可见性
- 静态库中的符号可见性和操作
- 未直接继承的基模板类成员的可见性
- 如何在可见性生效时导出公共内部/嵌套类
- 类中的内部成员可见性