开发者

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 开发者_如何学Gojust 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.


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.


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.


If you use object files, then all the code in the object file is placed in your application. If you use libraries, then only the required code is.


One reason is that objects in a .a library will only be pulled in to satisfy undefined symbol references - so if you want to allow the possibility for the calling application to define a symbol, or use a default definition in the "library" code, it's possible to do this with a real library but not with a single .o file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜