简体   繁体   中英

C++ project: Where to define global variable with function

I'm writing a C++ project where, at some point, I need to generate a list of random numbers, which I call "Zobrist" numbers. I tried to do something like this:

File "zobrist.h":

#ifndef ZOBRIST_H
#define ZOBRIST_H

namespace Zobrist
{
int ZOBRIST_NUMBERS[64];
bool ZOBRIST_NUMBERS_GENERATED;
void GENERATE_ZOBRIST_NUMBERS();
}

#endif // ZOBRIST_H

File "zobrist.cpp":

#include "zobrist.h"

bool Zobrist::ZOBRIST_NUMBERS_GENERATED = false;

void Zobrist::GENERATE_ZOBRIST_NUMBERS()
{
    for (uint i=0; i!=64; ++i) 
    {
        ZOBRIST_NUMBERS[i] = // Something
    }
    ZOBRIST_NUMBERS_GENERATED = true;
};

And then in several other files of my project, I want to include "zobrist.h" and write things like:

if (!Zobrist::ZOBRIST_NUMBERS_GENERATED) {Zobrist::GENERATE_ZOBRIST_NUMBERS();}
int x = Zobrist::ZOBRIST_NUMBERS[0] // etc.

However this does not compile and I don't understand why. I get errors like multiple definition of Zobrist::ZOBRIST_NUMBERS . (I tried throwing some "extern" key words in "zobrist.h" but it did not solve the errors.)

Where am I going wrong and what is the correct way to do this?

Your header file contains definitions of several variables, and that header is included in multiple source file, so multiple source files have their own copy of those variables. When you then attempt to link the compiled object files, it results in a multiple definition error.

You need to declare the variables in the header using the extern keyword, then define them in exactly one source files, probably zobrist.cpp. So your header would contain this:

namespace Zobrist
{
extern int ZOBRIST_NUMBERS[64];
extern bool ZOBRIST_NUMBERS_GENERATED;
void GENERATE_ZOBRIST_NUMBERS();
}

And zobrist.cpp would contain this:

bool Zobrist::ZOBRIST_NUMBERS_GENERATED = false;
int Zobrist::ZOBRIST_NUMBERS[64];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM