c++openglfreeglutglu

Calling gluPerspective and gluLookAt gives me an undefined reference?


I'm trying the following source, from Instant Glew:

#include <GL/glew.h>
#include <GL/freeglut.h>
#include <GL/glu.h>
#include <GL/gl.h>

void initGraphics()
{
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    const float lightPos[4] = {1, .5, 1, 0};
    glLightfv(GL_LIGHT0, GL_POSITION, lightPos);

    glEnable(GL_DEPTH_TEST);
    glClearColor(1.0, 1.0, 1.0, 1.0);
}

void onResize(int w, int h)
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glViewport(0, 0, w, h);
    gluPerspective(40, (float) w / h, 1, 100);
    glMatrixMode(GL_MODELVIEW);
}

void onDisplay()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glLoadIdentity();
    gluLookAt(0.0, 0.0, 5.0,
          0.0, 0.0, 1.0,
          0.0, 1.0, 0.0);

    glutSolidTeapot(1);
    glutSwapBuffers();
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE);
    glutInitWindowSize(500, 500);
    glutCreateWindow("Teapot");

    initGraphics();
    glutDisplayFunc(onDisplay);
    glutReshapeFunc(onResize);

    glutMainLoop();
    return 0;
}

My build setup is the Windows 10 VSCode, with MSYS2, and a Makefile like this:

OBJS = 01-teapot.cpp
OBJ_NAME = C:/<"MyProjectPath">/build/01-teapot
INC_PATH = -IC:/msys64/mingw64/include/GL -LC:/msys64/mingw64/include/GL
INC_LINK_LIBS = -lglew32 -lopengl32 -lfreeglut
compiling :
    g++ -Wall $(OBJS) $(INC_PATH) $(INC_LINK_LIBS) -o $(OBJ_NAME) -g

But the output is like:

C:\Users\<"myUser">\AppData\Local\Temp\cc5d3AtP.o: In function `onResize(int, int)':
c:\<"MyProjectPath">\PaPu_Instant_GLEW/01-teapot.cpp:22: undefined reference to `gluPerspective'
C:\Users\<"myUser">\AppData\Local\Temp\cc5d3AtP.o: In function `onDisplay()':
c:\<"MyProjectPath">\PaPu_Instant_GLEW/01-teapot.cpp:31: undefined reference to `gluLookAt'
collect2.exe: error: ld returned 1 exit status
make: *** [Makefile:32: compilando] Error 1

I really don't know where I'm failing. Did I forget to link some lib? I tried to add -lglut -lGLU already, on the linked libs, but the compiler can't find it...


Solution

  • gluLookAt is a function from the GL Utility library. You need to include -lglu32 in the linker options. It's explained in Using GLUT with MinGW.

    Also the order in which you give the libraries matter; see my related answer for reference. In your case, replace glfw3 with freeglut.

    I believe you are using GLUT and GLU for learning OpenGL which is okay but be informed that they were part of OpenGL 1 back in the day but is no longer an integral part of OpenGL and are deprecated. If you're doing production-level work, I'd recommend using a more mature library like GLFW (instead of GLUT/FreeGLUT); GLM has all the convenience functions that GLU provides. See towards the end of datenwolf's answer.