How to set a global vector within multiple files and VS projects in C++?

0

Here's a minimal reproducible example of what I'm trying to accomplish:

I'm trying to set up a standard vector that will contain a list of all the possible operations my program can use. These operations are defined using my class Option, which is defined in my classes.cpp file. I want it to be set initially in my main.cpp file, but it should be usable in my setter.cpp file, in which I fill the vector.

Here is my code:

Main.h

#pragma once
#include <vector>
#include "classes.h"

extern std::vector<Option*> OPTIONS;

Main.cpp

#include <iostream>
#include <vector>

#include "classes.h"
#include "setter.h"

std::vector<Option*> OPTIONS = {};

int main()
{
    initOptions(); //function from setter.cpp
    
    OPTIONS[0]->pFunc(); // EXCEPTION at 0xCCCCCCCC in Main.exe: 0xC0000005: Acccess infraction when executing 0xCCCCCCCC.

    return 0;
}

setter.h

#pragma once

void foo();
void initOptions();

setter.cpp

#include <iostream>
#include <string>

#include "Main.h"

void foo()
{
    std::cout << "Hello world :)" << std::endl;
}

void initOptions()
{
    OPTIONS = {
        &Option("Test String", &foo)
    };
}

classes.h

#pragma once

#include <string>

struct Option
{
    std::string name;
    void (*pFunc)();
    Option(std::string n, void (*pF)()) : name(n), pFunc(pF) {};
};

I'm using Visual Studio 2019, all Main and setter files are in the same project, but classes.h is in another one (I know maybe this is not the most efficient way of doing things, but this is one of my first "interesting" projects and I'm trying to experiment a bit).

It compiles just fine, but when I execute it throw the exception: EXCEPTION at 0xCCCCCCCC in Main.exe: 0xC0000005: Acccess infraction when executing 0xCCCCCCCC.. Using the inspection tool from VS I can see that the OPTIONS vector has one element, but it is empty (string is "" and function pointer is 0x00000000). Am I declaring the global vector wrong? Did I not link projects correctly? Thanks in advance!

P.D: I tried to minimize and translate my code (not native speaker), so if there is incorrect spelling it's probably my translation and not the actual code :P

c++
asked on Stack Overflow Jun 25, 2020 by lambda

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0