1. 程式人生 > >gcc編譯: 打包若干.o和.a檔案為新的.a檔案

gcc編譯: 打包若干.o和.a檔案為新的.a檔案

使用場景:

gcc編譯cpp的時候會生成.o , 然後若干.o檔案會打包生成.a檔案

但是有的時候是需要, 若干.o和多個.a, 打包生成 最終的一個.a檔案

*.o  --------\

xxx.a              --------->  des.a  

bbb.a ------/

方法:

編寫了一個指令碼, 複製並存儲為 rebuild_archive.sh, 直接在Makefile裡呼叫即可, 呼叫命令:
sh ./rebuild_archive.sh 目標.a    源.a ,,.... 源.o,,,,,</span>

sh ./rebuild_archive.sh  libdes.a  libda_frame.a libda_dso_dll.a_da.o libda_dso_dll.a_daconf.o libda_dso_dll.a_damain.o


#!/bin/sh


# Usage: sh rebuild_archive.sh  guo.a libda.sf_dll.a da_version.o 


if [ "$#" -lt "1" ]; then
echo "param error for archive rebuild.sh"
fi


#輸入引數集合
PARAM_STR=$*
# 目標檔案
TARGET=$1

TARGETTMPDIR=$TARGET.rebuild_archive
ARMACTEMPOBJ=$TARGET.rebuild_archive.ar.mac


test -d $TARGETTMPDIR && (echo "[FATAL]: some process running for $TARGET" && exit 0)
test -d $TARGETTMPDIR.2nd && (echo "[FATAL]: some process running for $TARGET" && exit 0)


rm -rf $TARGETTMPDIR
rm -rf $TARGETTMPDIR.2nd
mkdir -p $TARGETTMPDIR
mkdir -p $TARGETTMPDIR.2nd


echo OPEN ${TARGET} > $TARGETTMPDIR/$ARMACTEMPOBJ


for line in  ${PARAM_STR#* }
do
    SUFFIX=`echo ${line:0-2}`


    # 如果檔案字尾是 .a, 那麼解壓到.o 臨時資料夾
    if [ "$SUFFIX" = ".a" ];then
    #echo "this is .a : $line, extract it to tmpdir" 
    echo ADDLIB $line >> $TARGETTMPDIR/$ARMACTEMPOBJ
    fi


    # 如果檔案字尾是 .o, 那麼cp到臨時資料夾
    if [ "$SUFFIX" = ".o" ];then
    #echo "this is .o : $line, copy it to tmpdir" 
    cp -f $line $TARGETTMPDIR || exit $?
    fi


# 忽略其他檔案型別
# ignore other file types 
done


echo SAVE >> $TARGETTMPDIR/$ARMACTEMPOBJ
echo END >> $TARGETTMPDIR/$ARMACTEMPOBJ


# 打包目標
OOO_NUM=`ls ${TARGETTMPDIR}/*.o  | wc -l`
if [ "$OOO_NUM" -gt "0" ];then
cd ${TARGETTMPDIR} && ar crs ../${TARGET} ./*.o && cd - &&  ar -M < $TARGETTMPDIR/$ARMACTEMPOBJ || exit $?
else
sed -i 's/OPEN/CREATE /g' $TARGETTMPDIR/$ARMACTEMPOBJ 
ar -M < $TARGETTMPDIR/$ARMACTEMPOBJ || exit $?
fi




rm -rf $TARGETTMPDIR
rm -rf $TARGETTMPDIR.2nd