C++:与多个文件共享变量

C++: Share variables with Multiple files

我正在尝试在多个 .cpp 文件中共享全局变量。我用了extern关键字,但不符合我的要求

起初,我有四个文件:

***** common.hpp *****

#ifndef COMMON_HPP
#define COMMON_HPP
#include <iostream>
void printVar();
void printVarfromA();
void setVar(char *str);
#endif

***** Base.cpp *****

#include "common.hpp"
extern char *var;
void printVar(){
    std::cout << var << std::endl;
}
void setVar(char *str){
    var = str;
}

***** A.cpp *****

#include "common.hpp"
char *var = (char*)"This is var from A";
void printVarfromA(){
    printVar();
}

***** main.cpp *****

#include "common.hpp"
int main(){
    printVarfromA();
    setVar((char*)"Var was Changed.");
    printVarfromA();
    return 0;
}

一切顺利,结果是:

This is var from A
Var was Changed.

如我所料。

当我添加一个共享 var 变量的新文件时出现问题,比方说 B.cpp,它现在包含一行:

***** B.cpp *****

char *var;

这时候ld returned 1 exit status出现了ERROR

我尝试了很多方法,也搜索了很多,但没有得到任何解决方案。

我的问题。 如何在 C++ 中的多个文件中共享变量?

要在多个单元中共享同一个变量,您可以在除主单元之外的单元中使用extern变量。

// In file a.cpp
#include "A.hpp"
extern int global_x;
void AsetX()
{
    global_x = 12;
}
// In file b.cpp
#include "b.HPP"
extern int global_x;
void BsetX()
{
    global_x = 10;
}

在主单元中,在那里声明真正的变量。

#include "A.hpp"
#include "b.HPP"
int global_x;
int _tmain(int argc, _TCHAR* argv[])
{
    std::cout << global_x << std::endl;
    AsetX();
    std::cout << global_x << std::endl;
    BsetX();
    std::cout << global_x << std::endl;
    return 0;
}

输出将是

0
10
12

希望对您有所帮助。