Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a .o file and a .lib file?

Tags:

c

What is the difference between a .o file and a .lib file?

like image 732
reshefm Avatar asked Dec 09 '10 14:12

reshefm


2 Answers

A .LIB file is a collection of .OBJ files concatenated together with an index. There should be no difference in how the linker treats either.

Quoted from here:

What is the difference between .LIB and .OBJ files? (Visual Studio C++)

like image 116
Nawaz Avatar answered Sep 26 '22 02:09

Nawaz


Conceptually, a compilation unit (the unit of code in a source file/object file) is either linked entirely or not at all. While some implementations, with significant levels of cooperation between the compiler and linker, are able to remove unused code from object files at link time, it doesn't change the issue that including 2 compilation units with conflicting symbol names in a program is an error.

As a practical example, suppose your library has two functions foo and bar and they're in an object file together. If I want to use bar, but my program already has an external symbol named foo, I'm stuck with an error. Even if or how the implementation might be able to resolve this problem for me, the code is still incorrect.

On the other hand, if I have a library file containing two separate object files, one with foo and the other with bar, only the one containing bar will get pulled into my program.

When writing libraries, you should avoid including multiple functions in the same object file unless it's essential that they be used together. Doing so will bloat up applications which link your library (statically) and increase the likelihood of symbol conflicts. Personally I prefer erring on the side of separate files when there's a doubt - it's even useful to put foo_create and foo_free in separate files if the latter is nontrivial so that short one-off programs that don't need to call foo_free can avoid pulling in the code for deep freeing (and possibly even avoid pulling in the implementation of free itself).

like image 40
R.. GitHub STOP HELPING ICE Avatar answered Sep 22 '22 02:09

R.. GitHub STOP HELPING ICE