a.h 声明了一个 static int a=10; ```cpp // b.h #include "a.h" extern int a; // void func(); ``` ```cpp // b.cpp #include "b.h" #include <iostream> /* void func() { a=20; std::cout<<a<<std::endl; }*/ ```cpp ``cpp //c.h #include "b.h" extern int a; ``` ``cpp //c.cpp #include "c.h" #include <iostream> using namespace std; int main() { cout<<a<<endl; // func(); cout<<"***************"<<endl; cout<<a<<endl; return 0; } ```为什么静态全局变量a被多次包含没有报重复定义的错误
时间: 2024-04-01 20:32:56 浏览: 8
静态全局变量 a 在 b.h 中被声明为 extern,在 b.cpp 中被定义为 static int a=10; 这意味着它只能在 b.cpp 中使用,其他文件无法访问它。在 c.cpp 中包含了 c.h,而 c.h 又包含了 b.h,这样静态全局变量 a 被多次包含,但是因为它只能在 b.cpp 中使用,所以不会报重复定义的错误。在 main 函数中输出 a 的值也不会报错,因为 a 在 b.cpp 中被定义为静态变量,其作用域只限于 b.cpp,其他文件无法访问 a。
相关问题
cpp // a.h static int a=10; cpp // b.h #include "a.h" extern int a; // void func(); cpp // b.cpp #include "b.h" #include <iostream> /* void func() { a=20; std::cout<<a<<std::endl; }*/ cpp cpp //c.h #include "b.h" extern int a; ``` cpp //c.cpp #include "c.h" #include <iostream> using namespace std; int main() { cout<<a<<endl; // func(); cout<<"***************"<<endl; cout<<a<<endl; return 0; } ``` a.h中的静态全局变量在b.cpp和在c.cpp中是同一个变量吗
静态全局变量 a 在 a.h 中被定义,头文件 a.h 被包含在 b.cpp 和 c.cpp 中。由于 a 是静态变量,它只在定义它的源文件中可见,也就是说在 b.cpp 中的 a 和在 c.cpp 中的 a 是不同的变量。在 b.cpp 中的 a 的作用域仅限于 b.cpp,而在 c.cpp 中的 a 的作用域仅限于 c.cpp。因此,静态全局变量在 b.cpp 和 c.cpp 中不是同一个变量。
```cpp // a.h static int a=10; ``` ```cpp // b.h #include "a.h" extern int a; // void func(); ``` ```cpp // b.cpp #include "b.h" #include <iostream> /* void func() { a=20; std::cout<<a<<std::endl; }*/ ```cpp ``cpp //c.h #include "b.h" extern int a; ``` ``cpp //c.cpp #include "c.h" #include <iostream> using namespace std; int main() { cout<<a<<endl; // func(); cout<<"***************"<<endl; cout<<a<<endl; return 0; } ``` a.h中的静态全局变量a被多个源文件重复包含,为什么不报错
这里的静态全局变量 a 是在头文件 a.h 中被定义的,当多个源文件包含了 a.h 后,每个源文件的 a 都是独立的,它们在各自的文件作用域内是不同的变量。所以即使多个源文件都包含了 a.h,也不会出现重复定义的错误。但是需要注意的是,如果这些源文件中有文件包含了 b.h,并且使用了 extern int a; 来声明 a,由于 a 是一个静态变量,它的作用域只限于 a.cpp 文件内部,其他文件使用 extern int a; 声明的是另一个不同的变量,如果在这些文件中修改了 a 的值,对其他文件中的 a 不会产生影响。