我正在尝试创建一个 shell 脚本来制作 Makefile。我的策略是创建两个数组,一个包含所有.cpp 文件,另一个包含.cpp 后缀替换为.o。然后,我将 (grep | sed) 的返回值中的 .h 和 .ccp 文件分配给变量 temp,然后打印数组。但是我不断收到错误消息: “语法错误:无效的算术运算符(错误标记为“.o” 我的理论是 grep 的返回值没有正确存储在 temp 中 我对 bash 很陌生
cppfield=$(ls *.cpp)
x=0
for i in *.cpp; do
ofield[$x]="${i%.cpp}.o"
done
echo "$1 : ${ofield[@]}" > Makefile
echo " g++ -ansi -Wall -g -o $1 ${ofield[@]}" >> Makefile
for i in "${ofield[@]}"; do
temp=$(grep '#include "' ${cppfield[i]} | sed s/#include// | sed s/\"//g)
echo "${ofield[i]} : ${cppfield[i]} ${temp[@]}" >> Makefile
echo " g++ -ansi -Wall -g -c ${cppfield[i]}" >> Makefile
done
最佳答案
您要做的是找到依赖项,这可能通过 g++ -MM
更好地完成 - 它会为您指定的文件生成一个依赖项列表,您可以将其包含/在 makefile 中使用。
看这个文件的底部,我的 makefile 经常包含这样的东西:
include .depends
.depends: Makefile ${SOURCES}
${CXX} -MM ${CXXFLAGS} ${SOURCES} > $@
完整文件: https://github.com/Leporacanthicus/lacsap/blob/master/Makefile
在您执行以下操作之前,您的 grep 解决方案工作得相当好:
#if _WIN32
#include <windows.h>
#else
#include <someother.h>
#endif
或
/* Don't need this any more...
#include "blah.h
*/
关于c++ - 如何将实用程序 (grep/sed) 的返回值分配给数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28166712/