如何在C ++中创建可以访问多个文件的全局变量

时间:2018-11-23 18:29:06

标签: c# c++

我使用以下代码提供了全局变量。

namespace STR.Pref
{
    public static class Pref
    {
        public static Lang PrimaryLang { get; set; } = Lang.Sinhala;
        public static bool InsTrans { get; set; } = true;
        public static HotKey Key { get; set; } = new HotKey();
    }
}

因此,我可以使用以下代码将值分配给该全局变量(任何文件)。(无需实例化)

    private static void SetValue(Pref_tempObj tempObj)
    {
        Pref.Pref.Key = tempObj.Key;
        Pref.Pref.InsTrans = tempObj.InsTrans;
        Pref.Pref.PrimaryLang = tempObj.PrimaryLang;
   }

该程序运行良好,但是最近我对c ++感兴趣,因此我决定通过较小的更新就用c ++ / clr编写该程序。我对c ++有点陌生,我不明白如何使用c ++来完成此操作。(无论使用指针还是其他方式)

1 个答案:

答案 0 :(得分:1)

好的,我确实不建议这样做,但是您可以按照以下说明进行操作。

Global.h文件上(我的意思是在每个.cpp上都包含一个标头)

extern MyType MyTypeVar;

在.cpp上声明

MyType MyTypeVar

在要包含Global.h的每个.cpp上,都可以访问MyTypeVar

  

请参阅:

     

When to use extern in C++

     

Extern

     

What is the function of extern