Search code examples
c++openglnamespacesheader-filesglad

Can't use glGenBuffers in .h file C++


I'm trying to learn OpenGL in C++. To clean up my code I was trying to create an header file with all variables, which decribe objects, in it. This header looks something like this:

#pragma once

#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <stb/stb_image.h>

namespace data {

    ...

    float fragments[] = {...}
    int indices[] = {...}

    ...

}

I would like to add to this namespace also VAOs and VBOs, but as soon as I try to implement them using glGenBuffers and glGenVertexArray:

unsigned int VBO;
glGenBuffers(1, &VBO);

the IDE (Visual Studio) points me an error out, which says "this declaration doesn't include storage class or type identifier" (referred to glGenBuffer function; my editor is set to Italian, hence my translation might not be berfect). I've also tried to add a class inside this namesace (even if in my starting plans I wanted to avoid this approach):

#include <...>

namespace data {


    class Data {
 
        public:
            unsigned int VBO;
            glGenBuffers(1, &VBO)

    };
    

}

This time the error I get reads: "Missing explicit type. It is going to be used int" (referred to glGenBuffers function; holds what I wrote before: the translation might not be perfect, but I think it is understandable). As a last attempt, I've tried to implement the namespace in the main.cpp file too, under the main function. The error I get is the same as the first one, but if I use these function calls inside main, they work. I've also already written some other classes, such as shader.h or camera.h following this guide, and there I was able (using necessary includes such as glad/glad.h) to use gl* functions such as glCreateShader, glCreateProgram, glAttachShader and so on.


Solution

  • Snippet from OP:

    namespace data {
    
    
        class Data {
     
            public:
                unsigned int VBO;
                glGenBuffers(1, &VBO)
    
        };
    
    }
    

    This is a syntax error. glGenBuffers(1, &VBO) is a function call outside a function body block scope. You have to move it e.g. into the constructor of class Data. At best, you could put it into a lambda which is used as an initializer of Data::VBO:

    namespace data {
    
    
        class Data {
     
            public:
                unsigned int VBO
                  = []() { unsigned int VBO; glGenBuffers(1, &VBO); return VBO; }();
    
        };
        
    
    }
    

    Looks a bit convoluted? As glGenBuffers() expects a pointer, the local variable VBO has to be used inside the lambda. It's value is returned to initialize the member var. VBO. Of course, I could've given the local var. yet another name…

    Live Demo on coliru