简体   繁体   中英

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

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?

find ~/directory -type f -name "*.c" -print0 |
while IFS= read -r -d '' pathname; do
    gcc -o "${pathname%.c}" "$pathname"
done
find directory -type f -name "*.c" -exec sh -c \
  'cd $(dirname $1);make $(basename $1 .c)' sh {} \;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM