1. Writing outside the function means that it is visible in the current source file (to be precise, the .o object file generated by compilation, because visibility is actually the concept of the linker), which is an internal link. If you don't write it, it will be an external link, and you can use extern to reference this variable in other source files. a.cpp
static const int A = 0;
const int B = 0;
b.cpp
extern const int A; // 会发生链接错误
extern const int B; // 正确,多数是写在a.h里然后include
Written in a function means it is a static variable. Calling this function multiple times will share the same memory, instead of generating new ones on the stack.
void foo()
{
static const int A = 0; // 多次调用foo,&A不变。
const int B = 0; // 多次调用foo,&B不固定。
}
2. There is a method. For C++, it is recommended to use anonymous space instead of static to make the variables visible in this file.
If a global variable is modified by
static
, it is only visible in this file and cannot be used by other filesAnswer your two questions in one go~
static global variables are private for files. If not added, other files can also reference
Just add static
1. Writing outside the function means that it is visible in the current source file (to be precise, the .o object file generated by compilation, because visibility is actually the concept of the linker), which is an internal link. If you don't write it, it will be an external link, and you can use extern to reference this variable in other source files.
a.cpp
b.cpp
Written in a function means it is a static variable. Calling this function multiple times will share the same memory, instead of generating new ones on the stack.
2. There is a method. For C++, it is recommended to use anonymous space instead of static to make the variables visible in this file.