Link order for libraries C and C++

There are several advantages of using external libraries in C or C++. It saves a lot of effort as there are several wonderful C++ libraries out there to do just about anything. But there is one problem that many beginners face when beginning to use libraries. undefined reference to <function>.

Lets say we have a program that uses functions defined in an external library mylib. We can link it by adding -lmylib when we compile our code. So we do this:

g++ -lmylib main.c -o main    (incorrect order)

main.o: In function `main':
main.o(.text+0xf): undefined reference to `myfunc'

But mylib is linked and it has a definition for myfunc. The problem here is that the order of linking is important. The traditional behavior of linkers is to search for external functions from left to right in the libraries specified on the command line. This means that a function in libraryA is referenced from libraryB, libraryA should be linked after libraryB. This might often lead to circular dependencies when a library uses some function from another library which in turn uses a function from the first library. For example, if foo uses a function defined in bar and bar uses a function defined in foo, we would need to write:

g++ -o main -lfoo -lbar -lfoo

Although, this works well in practice and is used quite frequently, a much better solution to the above problem is to use the linker’s —start-group and —end-group options, like this:

g++ -o main -Wl,--start-group -lfoo -lbar -Wl,--end-group
Published 31 Jul 2012

I build mobile and web applications. Full Stack, Rails, React, Typescript, Kotlin, Swift
Pulkit Goyal on Twitter