How to add a struct to a vector from another class?

Viewed 70

I am student, and I am trying to build a project. My program is throwing an error while accessing the vector. The size of the vector is 1, but when I call RenderQueue.front it throws an error:

front() called on empty vector.

My code is below:

global.h

struct RenderStruct {
    std::function<void()> testfunction1;
    std::function<void()> testfunction2;
};
static std::vector<RenderStruct> RenderQueue;

Test.h

class test
{
public:
    static void add_to_queue();
};

Test.cpp

void test::add_to_queue()
{
        std::function<void()> testfunction1 = [&]()
        {
            std::cout << "First Function Working" << std::endl;
        };
        std::function<void()> testfunction2 = [&]()
        {
            std::cout << "Second Function Working" << std::endl;
        };
        RenderQueue.push_back({testfunction1, testfunction2}); 
};

Main.cpp

int main()
{
    test::add_to_queue();
    auto front = RenderQueue.front();

    front.testfunction();
    front.testfunction2();
};
1 Answers

static linkage variables are not shared between compilation units (cpp files).

Make your variable non static, mark it as extern, then export it from one cpp file (by declaring it without extern there).

Related