在ubuntu 10.10中编译和运行OpenGL(过剩)程序

fun*_*son 5 opengl

我写了这段代码:

#include <stdio.h>
#include <stdlib.h>
#include <GL/glx.h>    
#include <GL/gl.h>
#include <GL/glut.h>


void init()
{
    glClearColor(1.0,1.0,1.0,0.0);
    glMatrixMode(GL_PROJECTION);
    gluOrtho2D(0.0,200.0,0.0,150.0);
 }

 void lineSegment()
 {
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(0.0,0.0,1.0);
        glBegin(GL_TRIANGLES);
            glVertex2i(40,120);
            glVertex2i(40,20);
            glVertex2i(80,20);
        glEnd();
    glFlush();
 }
 int main()
 {
    glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
    glutInitWindowPosition(50,100);
    glutInitWindowSize(400,300);
    glutCreateWindow("An Example OpenGL....");
    init();
    glutDisplayFunc(lineSegment);
    glutMainLoop();
    return 0;
 }
Run Code Online (Sandbox Code Playgroud)

这是我的错误.

funfullson@funfullson:~$ gcc gl.cpp 
/tmp/cchfRGT2.o: In function `init()':
gl.cpp:(.text+0x2a): undefined reference to `glClearColor'
gl.cpp:(.text+0x36): undefined reference to `glMatrixMode'
gl.cpp:(.text+0x5a): undefined reference to `gluOrtho2D'
/tmp/cchfRGT2.o: In function `lineSegment()':
gl.cpp:(.text+0x6e): undefined reference to `glClear'
gl.cpp:(.text+0x8d): undefined reference to `glColor3f'
gl.cpp:(.text+0x99): undefined reference to `glBegin'
gl.cpp:(.text+0xad): undefined reference to `glVertex2i'
gl.cpp:(.text+0xc1): undefined reference to `glVertex2i'
gl.cpp:(.text+0xd5): undefined reference to `glVertex2i'
gl.cpp:(.text+0xda): undefined reference to `glEnd'
gl.cpp:(.text+0xdf): undefined reference to `glFlush'
/tmp/cchfRGT2.o: In function `main':
gl.cpp:(.text+0xf6): undefined reference to `glutInitDisplayMode'
gl.cpp:(.text+0x10a): undefined reference to `glutInitWindowPosition'
gl.cpp:(.text+0x11e): undefined reference to `glutInitWindowSize'
gl.cpp:(.text+0x12a): undefined reference to `glutCreateWindow'
gl.cpp:(.text+0x13b): undefined reference to `glutDisplayFunc'
gl.cpp:(.text+0x140): undefined reference to `glutMainLoop'
/tmp/cchfRGT2.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

我不知道我要做什么.请学习如何做到这一点.

Fré*_*idi 13

首先,您应该使用g++编译C++代码,而不是gcc.

然后,在构建程序时必须链接到OpenGL库:

$ g++ gl.cpp -o gl -lGL -lGLU -lglut
Run Code Online (Sandbox Code Playgroud)

上面的命令行将生成gl在当前目录中调用的可执行文件.如果没有-o,则调用生成的可执行文件a.out(在我的平台上),这可能不是您想要的.

(请注意,根据下面的密码注释,源文件必须在库选项之前g++才能编译它们.)


dai*_*isy 8

您必须将文件放在任何-l选项前面,这里举个例子:

g++ X.cpp -lX11 -lGL -lGLU -lglut -g -Wall -O2 -o X

还要确保已存在以下包:

sudo apt-get install mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev freeglut3-dev

并确保glx模块在Xorg中加载

Section "Module"
    Load "glx"
EndSection
Run Code Online (Sandbox Code Playgroud)

祝OpenGL编程好运!