c++ - C++项目: Where to define global variable with function

标签 c++ compiler-errors global-variables project

我正在编写一个C++项目,在该项目中,有时需要生成一个随机数列表,我将其称为“Zobrist”数。我试图做这样的事情:
文件“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
文件“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;
};
然后在项目的其他几个文件中,我想包含“zobrist.h”并编写如下内容:
if (!Zobrist::ZOBRIST_NUMBERS_GENERATED) {Zobrist::GENERATE_ZOBRIST_NUMBERS();}
int x = Zobrist::ZOBRIST_NUMBERS[0] // etc.
但是,这不能编译,我也不明白为什么。我收到类似multiple definition of Zobrist::ZOBRIST_NUMBERS的错误。 (我尝试在“zobrist.h”中抛出一些“extern”关键字,但是并不能解决错误。)
我在哪里出错,正确的方法是什么?

最佳答案

您的头文件包含几个变量的定义,并且该头包含在多个源文件中,因此多个源文件具有这些变量的自己的副本。然后,当您尝试链接已编译的目标文件时,将导致多定义错误。
您需要使用extern关键字在 header 中声明变量,然后在一个源文件(可能是zobrist.cpp)中定义它们。因此,您的标题将包含以下内容:

namespace Zobrist
{
extern int ZOBRIST_NUMBERS[64];
extern bool ZOBRIST_NUMBERS_GENERATED;
void GENERATE_ZOBRIST_NUMBERS();
}
zobrist.cpp将包含以下内容:
bool Zobrist::ZOBRIST_NUMBERS_GENERATED = false;
int Zobrist::ZOBRIST_NUMBERS[64];

关于c++ - C++项目: Where to define global variable with function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65571318/

相关文章:

c++ - 未找到 libpng "png_set_longjmp_fn"

compiler-errors - 重定位被截断以适应错误 : R_X86_64_32 against symbol

compiler-errors - vhdl错误: integer literal cannot have negative exponent

compiler-errors - 具有泛型编译错误的 Rust 结构

actionscript-3 - 使用 ActionScript 3 在帧之间传递变量

arrays - Grails中的全局数组?

c++ - 反向链接列表时,析构函数中的内存错误

c++ - gtest –– 使用 TEST_F 时 undefined symbol

c++ - 将静态库转换为DLL导致main之前的访问冲突

python - 定义全局变量的问题