如何从另一个.cpp文件访问全局结构

How to have access to global struct from another .cpp file?

本文关键字:访问 全局 结构 文件 cpp 另一个      更新时间:2023-10-16

in Surface.h我有:

struct Surface{
    bool isAllowedOnTile[TILETYPE_COUNT];
    float moveBecomes;  // When this is 0, it is ignored
    float moveChange;   // Is ignored if moveBecomes is non-zero
    float affChange[ELEMENT_COUNT];
    ID2D1BitmapBrush* pBrush;
};

在某些地方,我需要像这样初始化多个曲面:

Surface surface[SURFACEBMP_COUNT];
surface[0].moveBecomes = 123;
surface[0].moveChange = 0;
surface[0].affChange[0]= 2.0f;
...

然后我想要访问曲面[0],曲面[1],曲面[2]…从我的程序中的任何地方。我怎么做呢?

使用extern,并使surface全局

file.h

#ifndef FILE_H
#define FILE_H
...
extern Surface surface[SURFACEBMP_COUNT];
#endif

这是头文件,您应该在需要surface的地方包含它。

file.cpp

#include "file.h"
Surface surface[SURFACEBMP_COUNT];

在头文件中使用

最简单的方法
extern Surface surface[SURFACEBMP_COUNT];

然后在.cpp文件中声明并初始化它,并随时使用