Search code examples
c++linkage

map data structure doesn't show saved entries in main.cpp


I couldn't find any question related to this maybe because I don't know how to put it exactly. So I am creating a map with the static keyword in a header file and then saving entries to it in the source file. I tested the map in the source file and it saved the entries successfully. However, when I call the map in the main.cpp file to print out the entries, the map is empty. Can anyone help me with a way so that the map retains the entries when it's called in main?

I thought by making it static that the entries would remain in the map until the end of the program but it seems otherwise and I don't know another way. Thanks.


Solution

  • When an object is defined with the storage class static in a name space it has internal linkage. So in your case each compilation unit has its own map object.

    From the C++ (2014) Standard (3.5 Program and linkage)

    3 A name having namespace scope (3.3.6) has internal linkage if it is the name of (3.1)

    — a variable, function or function template that is explicitly declared static; or,

    ...

    You should declare the map with the keyword extern (instead of static) in the header and in one source file define the object.