gin
gin

Reputation: 316

Replace macro with function

I have a piece of macro which I used to check for opengl related error

#if (GL_ERROR_CHECK == On)
#define GL_CHECK(x)                                                                                                    \
    x;                                                                                                                 \
    {                                                                                                                  \
        GLenum glError = glGetError();                                                                                 \
        if(glError != GL_NO_ERROR)                                                                                     \
        {                                                                                                              \
            std::cout << "GL Error: " << glError << " at " << __FILE__ << ", " << __LINE__ << std::endl;               \
        }                                                                                                              \
    }
#else
#define GL_CHECK(x)  x;
#endif

and using it as such

GL_CHECK(glGenFramebuffers(1, (GLuint*)&m_u32FboID));
GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_u32FboID));

I am wondering if there is any way to replace this macro with a proper c++ function?

Upvotes: 0

Views: 197

Answers (2)

Carl
Carl

Reputation: 2067

If you are using OpenGL 4.3 and above you can use the Debug Callback instead so you don't have to wrap every GL function in a Macro: Check it out here

To enable everything:

glDebugMessageCallback(some_callback_function, nullptr);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, true);

With for example, this function:

void gl_debug_callback(GLenum source, GLenum type, GLuint id, GLenum severity,
                       GLsizei length, const GLchar* message, const void* userParam)
{
    std::cerr << "GL Debug Message: " << message << '\n';
}

Beware that this will sometimes output messages that are not errors, so you could consider switching on the severity for example, or be more restrictive about what you enable with the ...MessageControl function.

Upvotes: 4

R Sahu
R Sahu

Reputation: 206697

I am wondering if there is any way to replace this macro with a proper c++ function?

I think the macro is a sound option in this case. One of the main benefits of using the macro is that you are able to use __FILE__ and __LINE__ as part of the message.

You could move some of the code to a function but the macro still serves a purpose.

void checkForError(char const* file, int line)
{
   GLenum glError = glGetError();
   if(glError != GL_NO_ERROR)
   {
      std::cout << "GL Error: " << glError << " at " << file << ", " << line << std::endl;
   }
}

#if (GL_ERROR_CHECK == On)
#define GL_CHECK(x) x; checkForError(__FILE__, __LINE__);
#else
#define GL_CHECK(x) x;
#endif

Upvotes: 2

Related Questions