Search code examples
cpreprocessorstatic-librariesprefix

Copy SRC directory with adding a prefix to all c-library functions


I have a embedded C static library that communicates with a hardware peripheral. It currently does not support multiple hardware peripherals, but I need to interface to a second one. I do not care about code footprint rightnow. So I want to duplicate that library; one for each hardware.

This of course, will result in symbol collision. A good method is to use objcopy to add a prefix to object files. So I can get hw1_fun1.o and hw2_fun1.o. This post illustrates it.

I want to add a prefix to all c functions on the source level, not the object. Because I will need to modify a little bit for hw2.

Is there any script, c-preprocessor, tool that can make something like:

./scriptme --prefix=hw2 ~/src/ ~/dest/

I'll be grateful :)


Solution

  • I wrote a simple bash script that does the required function, or sort of. I hope it help someone one day.

    #!/bin/sh
    
    DIR_BIN=bin/ext/lwIP/
    DIR_SRC=src/ext/lwIP/
    DIR_DST=src/hw2_lwIP/
    CMD_NM=mb-nm
    
    [ -d $DIR_DST ] || ( echo "Destination directory does not exist!" && exit 1 );
    cp -r $DIR_SRC/* $DIR_DST/
    chmod -R 755 $DIR_DST # cygwin issue with Windows7
    sync                  # file permissions. (Pure MS shit!)
    
    funs=`find $DIR_BIN -name *.o | xargs $CMD_NM | grep " R \| T " | awk '{print $3}'`
    echo "Found $(echo $funs | wc -w) functions, processing:"
    for fun in $funs; 
    do
        echo "  $fun";
        find $DIR_DST -type f -exec sed -i "s/$fun/hw2_$fun/g" {} \;
    done;
    
    echo "Done! Now change includes and compile your project ;-)"