Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

c++ - Opengl linux undefined reference to basic functions

I wrote a program on Ubuntu 11.04 that uses freeglut. It worked fine. Then I got another computer and tried to run the program on a fresh install of Ubuntu 11.04. Doesn't work. So I installed

sudo apt-get install freeglut3 freeglut3-dev libglew1.5 libglew1.5-dev libglu1-mesa libglu1-mesa-dev libgl1-mesa-glx libgl1-mesa-dev mesa-common-dev gcc

and tried to run the program, which imports



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

using the command

g++ -lGL -lGLU -lglut Driver.cpp -o a

However the linker or whatever spits out like 200 errors of the form:



    Driver.cpp:(.text+0x3c6b): undefined reference to `glutSolidSphere'
    Driver.cpp:(.text+0x3c75): undefined reference to `glEnable'
    Driver.cpp:(.text+0x3c9a): undefined reference to `glColor4f'
    Driver.cpp:(.text+0x3cb5): undefined reference to `glRotatef'
    Driver.cpp:(.text+0x3d02): undefined reference to `glutSolidSphere'
    Driver.cpp:(.text+0x3d07): undefined reference to `glutSwapBuffers'

What is the cause of the problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The order in which you specify the objects you want to link to (including static and dynamic libraries) can matter.

Try with:

g++ Driver.cpp -lGL -lGLU -lglut  -o a

(Not sure about the order of the libs, but that looks ok.)

The idea when you build your command line is that if a requires a symbol from b, b must appear after a in the command line.

The link order problem happens (or not) with GCC/ld for shared libraries depending on (most likely among other things - I'm no expert here) whether the --as-needed link flag is set or not. (See for instance the before-last item in Gentoo's as-needed transition guide.)
The linking process eliminates un-needed symbols ASAP when --as-needed is active, which causes problems if the link order is not "correct". This is done to reduce the number of un-necessary dependencies present in final executables.
This doesn't happen (or less so) if --as-needed is not active - all symbols are kept in that case, and link order doesn't matter as much (more or less - again, I'm no expert.)

Since different distributions use different defaults for that flag, the behavior of GCC might seem inconsistent, but that's just an impression.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...