链接器错误:对符号'glOrtho'的未定义引用

时间:2013-07-20 20:31:22

标签: opengl linker-errors

我在Ubuntu 13.04(*mesa-common-dev freeglut3-dev*)中安装了OpenGL软件包,并尝试运行示例程序。

#include "GL/freeglut.h"
#include "GL/gl.h"

/* display function - code from:
     http://fly.cc.fer.hr/~unreal/theredbook/chapter01.html
This is the actual usage of the OpenGL library. 
The following code is the same for any platform */
void renderFunction()
{
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0, 1.0, 1.0);
    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
    glBegin(GL_POLYGON);
        glVertex2f(-0.5, -0.5);
        glVertex2f(-0.5, 0.5);
        glVertex2f(0.5, 0.5);
        glVertex2f(0.5, -0.5);
    glEnd();
    glFlush();
}

/* Main method - main entry point of application
the freeglut library does the window creation work for us, 
regardless of the platform. */
int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE);
    glutInitWindowSize(500,500);
    glutInitWindowPosition(100,100);
    glutCreateWindow("OpenGL - First window demo");
    glutDisplayFunc(renderFunction);
    glutMainLoop();    
    return 0;
}

但是,我遇到了这个错误,不知道该怎么做。

ved@vedvals:~/Desktop/p1$ g++ p1.cpp -lglut
/usr/bin/ld: /tmp/ccgGdeR2.o: undefined reference to symbol 'glOrtho'
/usr/bin/ld: note: 'glOrtho' is defined in DSO /usr/lib/x86_64-linux-gnu/mesa/libGL.so.1 so try adding it to the linker command line
/usr/lib/x86_64-linux-gnu/mesa/libGL.so.1: could not read symbols: Invalid operation
collect2: error: ld returned 1 exit status

我看了一下 OpenGL hello.c fails to build using CMake
因为错误类似,但我没有使用CMake

我的代码是错误的还是我需要包含/更改/调整某些设置?

我在此网站上提到了安装和代码:

Setting up an OpenGL development environment in Ubuntu Linux

2 个答案:

答案 0 :(得分:23)

您需要链接OpenGL库:

g++ p1.cpp -lglut -lGL

答案 1 :(得分:5)

您尚未链接OpenGL库,其中定义了glOrtho()。要使其工作,请使用g++ p1.cpp -lglut -lGL进行编译/链接。注意链接库的顺序,因为它在ld(g ++使用的链接器)中很重要。 GLUT库依赖于OpenGL,因此-lGL必须追踪-glut。这是因为ld仅在库中进行一个循环,因此如果链接-lGL -lglut,则不会定义从lglut到lGL的引用,从而产生链接错误。很抱歉这么长的答案,但我希望你能从中学到一些东西。