Home > Articles > Programming > Graphic Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Creating a Program Object and Linking the Shaders

Once the application has created a shader object for the vertex and fragment shader, it needs to create a program object. Conceptually, the program object can be thought of as the final linked program. Once each shader is compiled into a shader object, they must be attached to a program object and linked together before drawing.

The process of creating program objects and linking is fully described in Chapter 4. For now, we provide a brief overview of the process. The first step is to create the program object and attach the vertex shader and fragment shader to it.

// Create the program object
programObject = glCreateProgram();

if(programObject == 0)
   return 0;

glAttachShader(programObject, vertexShader);
glAttachShader(programObject, fragmentShader);

Once the two shaders have been attached, the next step the sample application does is to set the location for the vertex shader attribute vPosition:

// Bind vPosition to attribute 0
glBindAttribLocation(programObject, 0, "vPosition");

In Chapter 6, “Vertex Attributes, Vertex Arrays, and Buffer Objects,” we go into more detail on binding attributes. For now, note that the call to glBindAttribLocation binds the vPosition attribute declared in the vertex shader to location 0. Later, when we specify the vertex data, this location is used to specify the position.

Finally, we are ready to link the program and check for errors:

// Link the program

// Check the link status
glGetProgramiv(programObject, GL_LINK_STATUS, &linked);

   GLint infoLen = 0;

   glGetProgramiv(programObject, GL_INFO_LOG_LENGTH, &infoLen);

   if(infoLen > 1)
      char* infoLog = malloc(sizeof(char) * infoLen);

      glGetProgramInfoLog(programObject, infoLen, NULL, infoLog);
      esLogMessage("Error linking program:\n%s\n", infoLog);


    return FALSE;

// Store the program object
userData->programObject = programObject;

After all of these steps, we have finally compiled the shaders, checked for compile errors, created the program object, attached the shaders, linked the program, and checked for link errors. After successful linking of the program object, we can now finally use the program object for rendering! To use the program object for rendering, we bind it using glUseProgram.

// Use the program object

After calling glUseProgram with the program object handle, all subsequent rendering will occur using the vertex and fragment shaders attached to the program object.

  • + Share This
  • 🔖 Save To Your Account