Setup

The OpenGL has been originally provided on macOS. However, to ease our development, we need to install GLEW and GLFW using Homebrew, by brew install glew glfw.

The official GLEW website states: “GLEW provides efficient run-time mechanisms for determining which OpenGL extensions are supported on the target platform”. It’s a useful extension for developing OpenGL programs.

The package GLFW is an extension for managing windows. OpenGL is a bare-bones library which does not concern itself with the creation and management of windows. That job is made easy by GLFW.

Including and Linking on macOS

⚠️ Warning: On macOS you're not using libraries to include system level APIs, but Frameworks.

To include headers in source, use #include <OpenGL/gl.h> and #include <GLUT/glut.h>.

To link OpenGL libraries, use options -framework OpenGL and -framework GLUT.

Make sure to use something like #ifdef __APPLE__ when determining how to #include the headers, the rest of the world tends to follow the convention: <GL/gl.h>.

Minimal Compilation

The minimal compilation can be done by

1
  g++ main.cpp -o a.out -lglfw -lGLEW -framework OpenGL

where,

  • g++ is the compiler. No surprises here.

  • main.cpp is the file which contains the code (e.g. the above code) and is to be compiled

  • -o test.o specifies that the output executable should be named a.out

  • -lglfw and -lGLEW links the libraries GLFW and GLEW (which we installed via brew)

  • -framework OpenGL is the important flag which links the actual OpenGL framework to our code.

Note that, since our brew install path /usr/local/ is not in search paths by default, to make it available at system level, we can add search paths in .bashrc:

1
2
3
  export C_INCLUDE_PATH=/usr/local/include:$C_INCLUDE_PATH
  export CPLUS_INCLUDE_PATH=/usr/local/include:$CPLUS_INCLUDE_PATH
  export LIBRARY_PATH=/usr/local/lib:$LIBRARY_PATH

A Simple Makefile Sample

Here we provides a simple example of makefile, supposing we have main.cpp:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
  OPENGLLIB=-framework OpenGL
  GLEWLIB= -lGLEW
  GLFWLIB = -lglfw
  LIBS=$(OPENGLLIB) $(GLEWLIB) $(GLFWLIB)
  LDFLAGS=-L/usr/local/lib
  CPPFLAGS=-I/usr/local/include

  BIN=a.out
  SRCS=main.cpp
  INCLUDES=

  all: $(BIN)


  $(BIN): $(SRCS) $(INCLUDES)
      g++ $(CPPFLAGS) $(SRCS) -o $(BIN) $(LDFLAGS) $(LIBS)

  clean:
      rm -f *~ *.o $(BIN)