Issue
To create a static library, in general, we follow the 2-step method. First, we create object files for each source file using the 'gcc' command. Second, We will bundle all the object files using the 'ar' command.
I know 'gcc' and 'ar' are two separate components. But, I would like to get the confirmation on whether it is possible to create a static library in a single step using the 'gcc' command? If yes, Could anyone suggest how we can do that?
Note: This question is not related to how to create a static library. This question is purely to get confirmation. I referred gcc manual entry page but I couldn't find a way to do that.
Let me know your thoughts on this.
Solution
There is no way to create the archive library using gcc
only.
An approximation to the idea of a static library using GCC only is to create a relocatable object file containing all the component files:
gcc -r -o libobject.o object1.o object2.o object3.o
This creates a single object file, libobject.o
, that contains all the object code from the list of object files (object1.o
, object2.o
, object3.o
). It can be linked with any code that uses any of the functions to create an executable.
gcc -o program program.o libobject.o
Note that you must supply the path to the composite object file on the linker command line — it won't be found using a library search.
However, this is only an approximation to a static library because with a library, only the object files that provide functions used are linked into the executable, whereas with a composite object file like libobject.o
, all the code in all the object files is always linked into the executable. You rarely use every single function provided by a library in a single program.
Answered By - Jonathan Leffler Answer Checked By - Marie Seifert (WPSolving Admin)