Is it possible to setup something sort of like a class in C++ but in c in the simplest terms? I want to avoid using c++ but I would like to create a simple struct that has glsl shader program.

for example

struct shader_program
     GLuint shader;
     void (*create_shader)(const char* vss, const char* fss);
     void (*enableShader)(void);
     GLuint (*getUniformLoc(struct shader_program* sp, char* name);
     void (*disableShader)(void);


sample usage.

struct shader_program simple_shader = create_shader(.., ..);
struct shader_program advanced_shader = create_shader(.., ..);

 //...bind vai, draw, etc..



the main question is how would i set this up in a header and source file so that I can use a struct like this to do my rendering?

  • \$\begingroup\$ You are going to need function pointers. The struct defined in the header will be defined with function pointer members, and when you create objects of this type you will have to set those members to point at the functions you want them to use. \$\endgroup\$ – Alan Wolfe Jul 12 '15 at 20:34
  • \$\begingroup\$ simple_shader->enableShader() is going to be impossible. The closest you could get is simple_shader->enableShader(simple_shader). That's because C does not have a this keyword. That means functions (even if pointed to by the data of the struct) have no frame of reference to the variable you're using to call them, unless you explicitly pass it. I personally would recommend the approach of Honeybunchs answer, unless you have a reason to do simple_shader->enableShader(simple_shader) (the C version of a virtual function, effectively) \$\endgroup\$ – Wolfgang Skyler Jul 13 '15 at 19:43

If you want to aim for a real class, I would recommend C++ if that's how you want to organize your project. However C is still totally appropriate for OpenGL. If I'm not mistaken a totally appropriate C way of doing something class-like would be:

// Shader.h
struct Shader{
    GLuint id;

Shader* createShader(char* vertexSource, char* pixelSource);
void bindShader(Shader* shader);
void unbindShader();

Shader* createShader(char* vertexSource, char* pixelSource{
    //Load shader or whatever
    return new Shader(shaderID);

void bindShader(Shader* shader){
void unbindShader(){

void init(){
    shader = createShader("vert source", "pixel source);

void draw(){

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.