简体   繁体   中英

The order of the linked libraries C++ linker

I was debugging a project that depends on a set of libraries including libfreenect, OpenGL and OpenCL. The problem is that a black screen was the output.

As a debugging option, I have removed the OpenCL code and the linked library completely trying to make sure that OpenGL works fine and fortunately it does.

What I have noticed and do not understand is that my project works well using this order of libraries

 -lfreenect -lGL -lglut -lGLU -lOpenCL 

On the other hand, black screen is given while using this order

-lfreenect -lOpenCL -lGL -lglut -lGLU

My question is: why does the order of the linked libraries affect the output of the program ?

The OpenCL interface library installed on your system may pull in a different libGL.so than the libGL.so that shall eventually be loaded by your program. For example if you've got installed the Mesa OpenCL implementation but are using the NVidia driver, then linking against Mesa's OpenCL may pull in Mesa's libGL in conflict to the libGL required for OpenGL to work on your system; of course this is just guesswork.

Try using ldd on the produced program binary in either link order configuration and see which shared objects (in which paths) it's actually pulling in.

Think of it this way:

You have your object files compiled. Those files need extra methods, that are not there, and in the linking step you need to provide libraries that "cover" those needed methods, so it can create a neat executable.

For every library you give, the linker takes it, processes it, and if it founds methods that are needed, uses them. Then it rebuilds the table of missing methods, and continues with the next library included.

If you include OpenCL the first library, but your proyect does not directly call OpenCL methods, then the linker will discard that library. And later on when you include the library that needs OpenCL, it will trow a "undefined XXXXX method", because that library was already processed. Or, in your case, it may use another internal library different from the one you really intended to use.

A good rule is to include the "basic" libraries last, so that they get used in all the other libraries. In this case, OpenCL does not depend on any GL library so you should add it last.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM