Static global variables in C++

Static is a keyword with many meanings, and in this particular case, it means not global (paraphrasing)

It means that each .cpp file has its own copy of the variable. Thus, when you initialize in main.cpp, it is initialized ONLY in main.cpp. The other files have it still uninitialized.

First thing to fix this would be to remove the keyword static. That would cause the “Multiple definitions issue”. To fix this you should define the variable in a .cpp file and just extern declare it in a header file.


Edit: You are just allocating memory to it, doesnt count as initialization. You need to initialize the memory to 0 after allocation.

You can use new int[128]() instead of your more verbose malloc syntax, and this would perform initialization as well? Or you could take the easy road (thats what its there for) and use std::vector

Leave a Comment