Mr. Wizard
Mr. Wizard

Reputation: 1183

pass map from file to class c++

I have this situation where I'm trying to pass a map after I populated it, from a file to a class:

A.h - a normal header file where I have a function prototype and a map

#include <unordered_map>
func1();
static std::unordered_map<glm::ivec3, Chunk*, KeyHasher> chunks;

A.cpp

#include "A.h"
func1() {
    // ...
    chunks.insert(pair<glm::ivec3, Chunk*>(pos, chunk));
    cout << chunks.size(); // here I have the right size
    // ...
}

B.h

#include "A.h"
class B {
    public:
        my_func();
}

B.cpp

B::my_func() {
    // ...
    cout << chunks.size(); // size is 0
    for (auto& c : chunks) {
        // ... do something
    }
}

My question is, why in B.cpp chunks map arrives empty? I thought that if I use static this will solve my problem. Thank you for your time!

Upvotes: 0

Views: 76

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596652

You are declaring the chunks variable as static in A.h. That is the problem.

Every .cpp that #include's A.h will get its own copy of the chunks variable. That is why chunks is populated in A.cpp but is empty in B.cpp.

If you want to share the chunks variable across translation units, it needs to be declared as extern instead of static, and then defined in one of .cpp files, eg:

A.h

#include <unordered_map>
func1();
extern std::unordered_map<glm::ivec3, Chunk*, KeyHasher> chunks;

A.cpp

#include "A.h"

std::unordered_map<glm::ivec3, Chunk*, KeyHasher> chunks;

func1() {
    // ...
    chunks.insert(pair<glm::ivec3, Chunk*>(pos, chunk));
    cout << chunks.size(); // here I have the right size
    // ...
}

B.h

class B {
    public:
        my_func();
};

B.cpp

#include "B.h"
#include "A.h"

B::my_func() {
    // ...
    cout << chunks.size(); // here I have the right size
    for (auto& c : chunks) {
        // ... do something
    }
}

Upvotes: 3

Related Questions