C++变量范围在多个文件中

pet*_*234 1 c++ scope

如何在特定文件中创建可见变量/函数?例如,假设我有这样的文件层次:

extern int var;
Run Code Online (Sandbox Code Playgroud)

a.cpp

#include "a.h"

int var;
Run Code Online (Sandbox Code Playgroud)

BH

#include "a.h"

void function();
Run Code Online (Sandbox Code Playgroud)

b.cpp

#include "b.h"

void function() {
    var = 0;
}
Run Code Online (Sandbox Code Playgroud)

在main.cpp中我希望能够调用function(),但不能访问var变量

#include "b.h"

int main(int argc, char** argv) {
    function(); /* possible to call */
    var = 0 /* var shouldn't be visible */
} 
Run Code Online (Sandbox Code Playgroud)

我不希望文件啊被包含在main.cpp中 - 只有bh我怎样才能实现这个目标?

bam*_*s53 6

啊不需要包括在bh中,只有b.cpp.这是因为var只有函数定义需要它,而不是它的声明.除非你绝对必须这样做,否则这条规则不会在其他标题中包含标题.

BH

void function();
Run Code Online (Sandbox Code Playgroud)

b.cpp

#include "b.h"
#include "a.h"

void function() {
    var = 0;
}
Run Code Online (Sandbox Code Playgroud)