“Undefined” reference to class member in C++ [dupl

2019-09-05 04:33发布

问题:

This question already has an answer here:

  • Undefined reference to static class member 7 answers

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:

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.



标签: c++ oop gcc linker