Merging multiple libraries using GCC


Merging multiple libraries in a single library is quite simple using GNU Compiler Collection(GCC). GCC provides archiver which is used to create library (share and/or static) from object files. It can also be used to merge many libraries in a single one.

Creating a library using object files is quite simple and straight forward. Any one can run following command to create a library:

$> ar -r [Target_Library] [member object files]

For example if someone want to create a library 'libuser.a' using object files main.o, new.o, and old.o; he/she can issue following command:

$> ar -r libuser.a main.o new.o old.o

Merging of libraries is not straight forward. Archiver doesn't provide command line option to merge libraries instead it provides set of commands that can be run on archivers prompt. Archiver prompt can be invoked using

$> ar -M

command. From archiver prompt, run following sequence of commands to merge libraries:
  • - To create a new library:
    CREATE [name_of_target_library]
  • - Add library in previously created library:
    ADDLIB [library_to_add]
    Note: This command is to be run once, for each library to be added,
  • - Save the changes to created library:
    SAVE
  • - Come out of archiver prompt
    END

We can write all these commands in a macro, which can be passed as an arguement to archiver. A macro say 'ar.mac' can be passed to archiver using following command:

$>  ar -M <ar.mac

All these commands can be run from terminal. To merge libraries through makefile, We could write a generic makefile function, which dynamicaly creates, runs and then deletes macro for each merge operation.

Makefile code snippet is given below. It defines a makefile function which can be used to merge libraries:
#################################################
#FUNCTION: create_lib
#PARAMETER1: name of library to create
#PARAMETER2: List of object files to be merged
#DESCRIPTION: This function creates a temprory
# macro and then writes set of archiver commands
# required to merge the libraries. Launches
# archiver to run the macro.
#################################################
define create_lib
$(if $(wildcard $1),@$(RM) $1)
$(if $(wildcard ar.mac),@$(RM) ar.mac)
$(if $(filter lib%.a,$(notdir $2)),
@echo CREATE $1 > ar.mac
$(foreach LIB,$2,
     @echo ADDLIB $(LIB) >> ar.mac
 )
@echo SAVE >> ar.mac
@echo END >> ar.mac
@$(AR) -M <ar.mac
@$(RM) ar.mac
)
endef
#set of libraries to be merged
LIBS:= ./libs/libsoo.a ./libs/libfoo.a

#Target library
TARGET:= libt.a

#make-target to merge libraries
mergelibs:
        $(call create_lib, $(TARGET), $(LIBS))



1 comment:

Nishtha said...

very usefull.

Simple theme. Powered by Blogger.