首页 > 解决方案 > 如何在多个cpp文件中使用全局变量?

问题描述

常见的.h

extern char *gCert[] = {"Abdul", "Gotez", "Arhaim", "Erhan"};

模板.h

...

模板.cpp

#include "common.h"
char *gCert[];

void generateTemplate()
{
    for (int i = 0; i < 4; ++i)
    {
        /* code */
        printf("gCert[i]\n");
    }
}
    

主文件

...

主文件

#include "common.h"
char *gCert[];

void printRandomCert()
{
    srand(GetTickCount());
    int nSeed = rand() % 4;
    for (int i = 0; i < 4; ++i)
    {
        /* code */
        printf("gCert[(nSeed + i) % 4]\n");
    }
}

如您所见,我想gCert在多个 cpp 文件中使用,但不能这样使用。我在下面遇到错误
error LNK2005: "char * * gCert" (?gCert@@3PAPEADA) already defined in template.obj

像上面那样使用全局变量是不可能的吗?如果可能,请分享您的答案。

环境:Windows 10 x64、VisualStudio 2017 C++ Win32 应用程序和 DLL

标签: c++global-variablesmultiple-instances

解决方案


推荐阅读