【发布时间】:2015-05-07 10:27:12
【问题描述】:
好的,我一直在尝试在不同的源文件之间共享一个窗口上下文,主要是我的主 c++ 文件和主游戏循环,它看起来像这样(精简),它是在 OpenGL 3.3 和 GLFW 3 中使用代码制作的: : 块 13.12。我正在尝试这样做以减少我的个人文件的大小
每次我尝试编译时都会得到:
mutiple definitions of 'window'
在 mainLoop.cpp 文件中。
WINDOW.h
#ifndef WINDOW_H
#define WINDOW_H
//include glfw etc...
GLFWwindow* window;
#endif //WINDOW.h
mainLoop.cpp
//include glfw etc...
#include "WINDOW.h"
void mainLoop()
{
do{
//some code that uses 'window' context
}while( glfwGetKey( window, GLFW_KEY_ESCAPE ) != GLFW_PRESS && glfwWindowShouldClose( window ) == 0 ); //<- "window" causing problems
}
//relevant cleanup
main.cpp
//include necessary headers (glfw, glu, glew, and others)
#include "WINDOW.h"
void mainLoop();
int main( void )
{
//initialize opengl and whatnot.
window = glfwCreateWindow( 512, 288, "NULL", NULL, NULL );
glfwMakeContextCurrent( window );
mainLoop();
}
我不知道为什么我不能以这种方式使用上下文,如果我的“mainLoop”代码本身在 main 中(使用 WINDOW.hpp),它就可以工作。 非常感谢您的帮助。
【问题讨论】:
-
它与 GLFW 无关。您现在将
window.h包含在两个源文件中,因此变量window被定义了两次。如果你真的想要一个全局变量,你可以看看相关的问题:How can I use extern to share globe variables between source files in C++? -
@Leiaz 在“GLFWwindow* window”上使用 extern 只是出于某种原因给了我对“window”的未定义引用。
-
那是因为
extern只是声明了变量,它仍然需要在某个地方实际定义(在 cpp 文件中),但只需定义一次。 -
为什么不把它作为参数传递给
mainLoop? -
@Leiaz 我认为 window = glfwCreateWindow() 是定义?