glGetAttribLocation
Asks a linked program which location the linker gave a vertex input; -1 if it does not exist.
Part of the family glGet*
Signature
GLint glGetAttribLocation(GLuint program, const GLchar *name);
How it works
If the vertex shader does not say layout(location = N), the linker picks the locations itself, and the C++ side has to ask for them by name before calling glVertexAttribPointer.
Writing layout(location = N) in the shader is simpler and safer: the numbers are fixed and visible in both places, so this function is mostly found in older code. It returns -1 when the name is wrong, or when the input exists but is never used and the compiler removed it.
Parameters
A successfully linked program.
The input's name in the vertex shader, e.g. "aPos".
Return value
The location (0, 1, …), or -1 if there is no active input with that name.
Tips & pitfalls
Never pass -1 on to
glVertexAttribPointerorglEnableVertexAttribArray: as a GLuint it becomes 4294967295 and raises GL_INVALID_VALUE.
Errors
When the call is invalid it does nothing and sets an error, which glGetError returns:
- GL_INVALID_OPERATION
- program has not been linked successfully.
Example
1GLint posLoc = glGetAttribLocation(program, "aPos");
2if (posLoc >= 0) {
3 glVertexAttribPointer(posLoc, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *)0);
4 glEnableVertexAttribArray(posLoc);
5}