前面写了一篇文章《Linux C/C++工程中可生成ELF、动/静态库文件的通用Makefile》,里面的Makefile代码有个不好的地方需要修改。当编译.cpp文件时,使用的STD_OPT
变量仍然是编译.c文件时的参数-std=c99
,这个在C++中是不支持的。
由于sed命令可用的参数太多了,这里只列举脚本中用到的几个参数:
1 2 3 | sed -i:直接修改文件而不是将处理的结果在屏幕上输出; sed -e:多个操作action按顺序执行; sed -e '/help:/ a 要追加的内容':表示在help:文字后面追加内容。 |
---|
代码比较简单,直接执行命令./handle_makefile.sh
即可。其中handle
函数主要用到了正则替换,追加,删除这三个action操作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | #!/bin/bash # FileName: handle_makefile.sh # Description: Simple usage of sed command to modify many Makefiles in batch processing. # Simple Usage: ./handle_makefile.sh # (c) 2016 vfhky https://typecodes.com/linux/handlemakefilebysed.html # https://github.com/vfhky/shell-tools/blob/master/filehandle/handle_makefile.sh # Dir to be handled. SRC_DIR="/home/vfhky/shell" # The makefile you want to modify. SEARCH_NAME="Makefile" #### # @param: $1 Name of the file #### function handle() { echo -e 'Handling file='$1'' sed -i \ -e 's/-std=c99 -D_GNU_SOURCE /-D_GNU_SOURCE/' \ -e 's/CC += $(STD_OPT)/CC += -std=c99 $(STD_OPT)/' \ -e '/help:/ a\ @echo CC=$(CC)\ @echo CXX=$(CXX)\ @echo CFLAGS=$(CFLAGS)\ @echo CXXFLAGS=$(CXXFLAGS)' \ -e '/ @echo STD_OPT=[$(STD_OPT)]/d' \ -e '/ @echo CFLAGS=[$(CFLAGS)]/d' \ $1 #echo "" | awk '{fflush()}' } # Get the target files you want to modify. ALL_MAKEFILE=$(find ${SRC_DIR} -type f -name ${SEARCH_NAME}) # Traverse the target files. for FILE in ${ALL_MAKEFILE} do handle ${FILE} if $? -gt 0 ; then echo 'failed.' #echo "" | awk '{fflush()}' fi done |
---|
如上图所示,脚本不断遍历src目录下的Makefile文件,然后进行处理。
目前已经把这个脚本放在Github了,地址是https://github.com/vfhky/shell-tools,以后脚本的更新或者更多好用的脚本也都会加入到这个工程中。