the order of linking libraries

A common compiling command is as follows:

g++ a.cpp b.cpp -o app.exe -I include1dir -I include2dir -l libray1.a -l libray2.a -L libdir1 -L libdir2

The application is compiled out of two source files: a.cpp, b.cpp and two libraries: library1.a, library2.a.

In most cases, the order of the linking libraries does not matter. So you can type the command as follows:

g++ a.cpp b.cpp -o app.exe -I include1dir -I include2dir  -l libray2.a -l libray1.a -L libdir1 -L libdir2

However, if libray1.a depends on libray2.a, i.e., libray1.a has references to libray2.a, the link order is important. You should put libray1.a before libray2.a, and the linker will find referenced symbols in current library in libraries afterwards. If you put libray2.a before libray1.a, linker will not find the referenced symbols(such as function names) and generate errors like “undefined reference to xxx”.

Comments are closed, but trackbacks and pingbacks are open.