16

I have multiple versions of a library, all with the same name (boost libraries), each installed in its own directory. I know how to instruct the compiler and linker to search in certain directories for header files and libraries (-I and -L). I am also aware of how to pass the actual library file to the linker.

My question is how to specify precedence in the search path of the compiler and the linker, such that it searches folder A before searching folder B and takes A's version of the library instead of B's . I'm interested in order between all eligible directories, i.e. the default gcc and g++ ones, and the ones specified after -I and -L.

My distro is Ubuntu 14.04, and I use g++ 4.8 up to 6.

Community
  • 1
  • 1
narengi
  • 1,345
  • 3
  • 17
  • 38

1 Answers1

25

GCC will search your -I directories in the left-to-right order in which they appear in your commandline and it will search all your -I directories before the default #include directories. Here is the documentation.

GCC invokes the system linker, ld, to perform linkage. Occurrences of GCC's -L option, and its -l option, are passed through to the linker with their order preserved.

The linker will search your -L directories in the left-to-right order in which they appear in the commandline and it will search all your -L directories before the default linkage directories. All of the -L options, in the order specified, apply to all of the -l options, regardless of how -L and -l options are intermixed in the commandline. E.g.

-La -lfoo -Lb -lbar

is equivalent to any of:

-La -Lb -lfoo -lbar
-lfoo -La -Lb -lbar
-lfoo -lbar -La -Lb

Here is the documentation

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
  • Hm... But it's still unclear whether it will _stop_ searching once it hits the required include file, or it will exhaust the search. In other words, does the first or the last win. It's not automatically obvious... – Zeus Feb 14 '23 at 04:40