0

common.h

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

template.h

...

template.cpp

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

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

main.h

...

main.cpp

#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");
    }
}

As you see, I'd like to use gCert in multiple cpp files, but cannot use like this. I got an error below
error LNK2005: "char * * gCert" (?gCert@@3PAPEADA) already defined in template.obj

Is it impossible to use global variable like above? If possible, please share your answers.

Environment: Windows 10 x64, VisualStudio 2017 C++ Win32 Application & DLL

AleXelton
  • 767
  • 5
  • 27
  • 3
    why do you define it again in `main` ? – 463035818_is_not_an_ai Dec 14 '20 at 13:09
  • I didn't write full contents, but I have to use globalvar-gCert again in main.cpp – AleXelton Dec 14 '20 at 13:17
  • you use the one declared in `common.h`. – 463035818_is_not_an_ai Dec 14 '20 at 13:19
  • then how can I use global variable several times in one project? I think I just made a mistake, but I'd like to solve it – AleXelton Dec 14 '20 at 13:22
  • 2
    like you already do, just don't define it twice. Or perhaps just don't use global varaibles ;) – 463035818_is_not_an_ai Dec 14 '20 at 13:22
  • thank you @largest_prime_is_463035818, how can I use initialized char** var as member var in a class? – AleXelton Dec 14 '20 at 13:23
  • 2
    related: https://stackoverflow.com/questions/10422034/when-to-use-extern-in-c. Why would you use a `char**` as member? Do you want a `std::vector>` ? – 463035818_is_not_an_ai Dec 14 '20 at 13:24
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/225932/discussion-between-g-alexander-and-largest-prime-is-463035818). – AleXelton Dec 14 '20 at 13:25
  • 3
    Just like your error message and previous commentators tells you, you have defined `gCert` in both `template.cpp` and `main.cpp`. It should only have one definition. Maybe start by going back to a book or tutorial that covers this topic so you get an understanding for how `extern` is used. IMO it seems to be a question with a lack of research from your part. This is just not how it's done and any tutorial or book will tell you that. – super Dec 14 '20 at 13:31
  • @G.Alexander In C++17 and later you can make it an [inline variable](https://en.cppreference.com/w/cpp/language/inline). – dxiv Dec 14 '20 at 20:56

0 Answers0