Search code examples
javaandroidc++extern

How to have a global variable in C++


I'm rewriting someone's code who had a global variable that is useful during initialization when Java makes it's callbacks into C, and just after. It appears they have declared this variable in several places with an extern prefix and once without. I don't really see why they would do this to a global variable (prefixed g_) when I would rather call it static and declare it just once.

Would I be able to do this or does static have negative connotations for thread safety in this context? The bulk of my code is C++ but there is some extern 'C' stuff like those functions Java calls into.

Currently I'm not using extern or static but I'm inclined to believe this is why I'm getting linking errors.


Solution

  • static does not prevent a variable from being duplicated during the compilation of multiple compilation units. When you link those compilation units, they will end up seeing different "instances" of the same variable. In other words, each one will see its own copy.

    The usefulness of extern is exactly to avoid this duplication. You declare the global (non-static) variable in an implementation file (.c) and declare it as extern on a given header file (.h) to be included by every source file that depends on it.