How to search subdirectories for .c files and compile them (shell scripting)

不羁岁月 提交于 2019-12-12 06:48:30

问题


I need to take an argument which is a directory of the current directory and search its folders and compile any C files in those folders. I'm just beginning shell scripting in Bash and am a little over my head.

So far things I've tried included using find to search for the files and then pipe it to xargs to compile but kept getting an error saying that testing.c wasn't a directory.

find ~/directory -name *.c | xargs gcc -o testing testing.c

I've also tried ls -R to search folders for .c files but don't know how to then take the paths as arguments to then move to and compile?


回答1:


find directory -type f -name "*.c" -exec sh -c \
  'cd $(dirname $1);make $(basename $1 .c)' sh {} \;



回答2:


find ~/directory -type f -name "*.c" -print0 |
while IFS= read -r -d '' pathname; do
    gcc -o "${pathname%.c}" "$pathname"
done



回答3:


As @shx2 suggested, using make (or some other build system) would arguably be the best approach. You don't want to go compiling files in some source tree without a proper build system.



来源:https://stackoverflow.com/questions/16621187/how-to-search-subdirectories-for-c-files-and-compile-them-shell-scripting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!