Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++. Advantages of libraries over combined object files

While it is commonplace to combine multiple object files in a library, it is possible (at least in Linux) to combine multiple object files into another object file.

(See combine two GCC compiled .o object files into a third .o file)

As there are downsides to using libraries instead of just combined object files:

1: It's easier to work with only one type of file (object) when linking, especially if all files do the same thing.

2: When linking (At least in GCC), libraries (by default) need to be ordered and can't handle cyclic dependencies.

I want to know what advantages there are to libraries (apart from the catch 22 that they're used lots).

After searching for a while, the only explanation I get seems to be that single libraries are better than multiple object files.

like image 735
Simon Avatar asked Jun 05 '11 13:06

Simon


2 Answers

While it depends on the linker being used, object files are being included in the final binary in their entirety. So, if you combine several object files into one object file, then the resulting (combined) object file is included in the resultant binary.

In contrast, a library is just that, a library of object files. The linker will only pull the object files from the library that it needs to resolve all the symbolic links. If an object file (in the library) is not needed, then it is not included int the binary.

like image 128
Foredecker Avatar answered Sep 20 '22 07:09

Foredecker


Generally library is better since linker can optimize out unused .o files in library.

Combining the files somehow has some advantages too:

  • If you combine all your source files into one then that tremendously increases compilation speed.
  • Sometimes in C++ the linker may optimize out .o file that you did not want to be optimized out. For example when you need side-effects of constructors of objects defined there but not used in any other translation unit.
like image 32
Öö Tiib Avatar answered Sep 19 '22 07:09

Öö Tiib