0

I have a vector in a DLL visual studio project that i would like to use in my executable project and another DLL. I want the all projects to be using the same instance of the vector. I dont want each project to create their own instance. How can i do this?

//  DLL A project
//  A.h
extern std::vector<int> ids;

//  A.cpp
std::vector<int> ids;

//  DLL B project
//  B.h
void foo();

//  B.cpp
#include "A.h"

void foo()
{
    ids.push_back(2);
}



//  executable project
//  main.cpp
#include "A.h"
#include "B.h"

int main()
{   
    foo();
    ids.push_back(1);

    //  should print 21
    for(auto i : ids)
    {
        std::cout << i << std::endl;
    }
    return 0;
}
SRG
  • 249
  • 3
  • 13
  • Export it as an array? – fstam Mar 12 '19 at 19:49
  • https://learn.microsoft.com/en-us/cpp/cpp/dllexport-dllimport?view=vs-2017 – R Sahu Mar 12 '19 at 19:51
  • There is nothing special about variables, you import/export them basically the same way you do functionss –  Mar 12 '19 at 19:51
  • 2
    " I want the all projects to be using the same instance of the vector" - You probably don't. Global variables have a bad reputation for many good reasons. Also, research "static initialization fiasco". Also think about the fact that shared libraries (DLLs) can be loaded/unloaded at any time - what happens if the dll owning the object is unloaded? I think you want to re-think your design to *not* want/need this. – Jesper Juhl Mar 12 '19 at 19:51
  • Tooting my own horn: https://stackoverflow.com/a/48350295/434551. – R Sahu Mar 12 '19 at 19:57

1 Answers1

0

Had to add this to my DLL projects and the executable project. USE_DLL is only defined in the DLL project that has the .h/.cpp in it.

#ifdef USE_DLL
#define DllAPI   __declspec( dllexport )
#else
#define DllAPI   __declspec( dllimport )
#endif
SRG
  • 249
  • 3
  • 13