C ++ / C在Visual Studio中的2个项目之间共享全局变量

时间:2013-11-18 19:10:46

标签: c++ variables global projects

在VS中,我有一个包含2个项目的sln:

项目A:

A.H

#include <string>
extern bool flag;    

A.cpp

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

void funcA()
{
  int i = 0;
}

项目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 ;
}

我将projectA设置为DLL,将projectB设置为EXE。

在链接中,我收到错误:错误LNK2001:未解析的外部符号“bool flag”(?flag @@ 3_NA)

我应该在设置中手动指定projectB到projectA吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

像这样:

<强> 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;
}

B.hB.cpp无需更改)