简体   繁体   English

C++ 项目:在哪里用 function 定义全局变量

[英]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.我正在编写一个 C++ 项目,在某些时候,我需要生成一个随机数列表,我称之为“Zobrist”数字。 I tried to do something like this:我试图做这样的事情:

File "zobrist.h":文件“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":文件“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:然后在我项目的其他几个文件中,我想包含“zobrist.h”并编写如下内容:

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 .我收到诸如multiple definition of Zobrist::ZOBRIST_NUMBERS类的错误。 (I tried throwing some "extern" key words in "zobrist.h" but it did not solve the errors.) (我尝试在“zobrist.h”中加入一些“extern”关键词,但并没有解决错误。)

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.您的 header 文件包含多个变量的定义,并且 header 包含在多个源文件中,因此多个源文件有自己的这些变量的副本。 When you then attempt to link the compiled object files, it results in a multiple definition error.然后,当您尝试链接已编译的 object 文件时,会导致多定义错误。

You need to declare the variables in the header using the extern keyword, then define them in exactly one source files, probably zobrist.cpp.您需要使用extern关键字声明header 中的变量,然后在一个源文件中定义它们,可能是 zobrist.cpp。 So your header would contain this:因此,您的 header 将包含以下内容:

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

And zobrist.cpp would contain this:并且 zobrist.cpp 将包含以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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