Code snippets: GLEW and assert

I’ve been using GLEW to handle my OpenGL extensions and I like using assert when developing test programs that require certain extensions.

The thing I like about assert is that it exits the program and prints out the error, file, and line number. That’s more of less what I would do using more lines of code (meaning more chance of stupid errors) or my own macro (why reinvent the wheel?). It also encourages the use of descriptive variable names (like “num_draw_buffers” instead of “n”) so that the error output is more meaningful.

Here’s a snippet from some recent code:

glewInit();

/* These extensions must be supported */
assert(glewGetExtension("GL_ARB_vertex_shader"));
assert(glewGetExtension("GL_ARB_fragment_shader"));
assert(glewGetExtension("GL_ARB_texture_rectangle"));
assert(glewGetExtension("GL_EXT_framebuffer_object"));
assert(glewGetExtension("GL_ARB_draw_buffers"));

/* There must be at least 2 draw buffers */
{
    GLint num_draw_buffers;

    glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &num_draw_buffers);

    assert(num_draw_buffers >= 2);
}

Finally, if you ever decide that you don’t need assertions (because your code is clearly perfect), #define NDEBUG disables them. Good stuff!

Leave a Reply

Your email address will not be published. Required fields are marked *