在C++中声明头文件中的全局结构

Tal*_*zig 0 c++ opengl structure declaration global-variables

我在头文件中创建了一个结构,如下所示:

typedef struct
{
    GLfloat lgtR, lgtG, lgtB, lgtA;
    GLfloat x, y, z;
    bool islight;
    GLfloat width, height, depth;
    GLenum lightn;
    particle prt;
    int maxprt;
} emitter;
Run Code Online (Sandbox Code Playgroud)

这没有问题.

但是,在那个特定的头文件中,我想声明一个可以在所有函数中使用的全局发射器,它不是主源文件的一部分:

// header.h global declaration

emmiter currentEmit;

GLvoid glSetEmitter(emitter emitter)
{
    currentEmit = emitter;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试这个时,我得到了很多"错误C2228:'.variable'的左边必须有class/struct/union,所以我假设它根本没有声明我的结构.

有没有办法在头文件中全局声明该结构,如果是这样,是否还有一种方法可以防止它成为其他.cpp文件的一部分?

Luc*_*ore 7

emitter是不一样的emmiter.

此外,由于这是C++ - 只是struct {};直接写,没有必要typedef.

您的整个标题是错误的,如果包含在多个翻译单元中,它将提供多个定义:

// header.h global declaration
extern emitter currentEmit;   // <-- note extern

inline GLvoid glSetEmitter(emitter emitter)  // <-- note inline
{
    currentEmit = emitter;
}
Run Code Online (Sandbox Code Playgroud)

currentEmit需要在单个实现文件中定义,而不是标头.该功能需要是inline所有TU都没有定义的.

最后一件事:通过const引用传递参数:

inline GLvoid glSetEmitter(const emitter& emitter)  // <-- note inline
{
    currentEmit = emitter;
}
Run Code Online (Sandbox Code Playgroud)

否则将创建不必要的副本.