Search code examples
c++variablesglobalprojects

C++/C Shareing global variable between 2 projects in Visual Studio


In VS, I have a sln including 2 projects:

Project A:

A.h

#include <string>
extern bool flag;    

A.cpp

#include "A.h"
bool flag = false;

void funcA()
{
  int i = 0;
}

Project B:

B.h

#include <stdio.h>

B.cpp

#include "B.h"
#include "..\ProjectA\A.h"

void main()
{
    int j = 10;
    flag  = true;
    std::cout << j << "\n" << flag ;
}

I set projectA as DLL, projectB as EXE.

In linking, I get the error: error LNK2001: unresolved external symbol "bool flag" (?flag@@3_NA)

Should I manually specify projectB to projectA in setting?

Thank you.


Solution

  • Like this:

    A.h

    #ifndef LIBA_API
    #define LIBA_API __declspec(dllimport)
    #endif
    
    extern LIBA_API bool flag;    
    

    A.cpp

    #define LIBA_API __declspec(dllexport)
    #include "A.h"
    LIBA_API bool flag = false;
    
    void funcA()
    {
      int i = 0;
    }
    

    (no changes needed to B.h or B.cpp)