So I'm learning OpenGL on learnopengl.com. To make my code as clear as possible i decided to split it up into different files and connect them with a header file. I declared an extern variable shaderProgram in a header file and defined it in a setupShaders() function. However when I run the code (I'm using Visual Studio 2019) I get an error, that this variable is not defined. The weird thing is that I use this variable in this same function, just after defining and it still doesn't work.
//header.h
extern unsigned int shaderProgram;
//shader.cpp
void setupShaders(){
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader); // error
}
Obviously, that's a big simplification of the code
The code you have shown is not defining the variable at all. You have declared it as extern
, and you are assigning a value it inside your setupShaders()
function, but you are not actually defining any storage for the variable. You need to add that to your .cpp
file, eg:
header.h
extern unsigned int shaderProgram;
shader.cpp
unsigned int shaderProgram; // <-- HERE
void setupShaders(){
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
}