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

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

本文关键字:两个 项目 之间 全局变量 共享 Visual Studio C++      更新时间:2023-10-16

在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 "..ProjectAA.h"
void main()
{
    int j = 10;
    flag  = true;
    std::cout << j << "n" << flag ;
}

我将项目A设置为DLL,将项目B设置为EXE。

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

我应该在设置中手动指定项目B到项目A吗?

谢谢。

像这样:

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