1

While linking this code:

#include <map>
using std::map;
#include <string>
using std::string;
class C {
public:
    static void dump() {
        for (const auto& e : data) {
            string(e.first);
        }
    }
private:
    static map<string,map<string,string>> data;
};
int main() {
    C::dump();
}

... I get this error:

/tmp/cc4W2iNa.o: In function `C::dump()':
test.cpp:(.text._ZN1C4dumpEv[_ZN1C4dumpEv]+0x9): undefined reference to `C::data'
collect2: error: ld returned 1 exit status

... from g++ (GCC) 4.9.1. Am I doing anything wrong?

1 Answers1

8

You've declared C::data, but not defined it. Add a definition outside the class:

map<string,map<string,string>> C::data;

In a larger program, which more than one source file, this must go in just one source file to satisfy the One Definition Rule; while the class definition (including the declaration of data) might go in a header to be available wherever it's needed.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644