Home > Net >  Compile .c file that contain specific word in bash script
Compile .c file that contain specific word in bash script

Time:04-15

How can we compile ".c" files in an input folder that contains a specific word in bash? (It doesn't matter if a part of the word is in uppercase or lower case)
I try this:

find $foldername -type f -name "*.c" | while read filename; do
    # gcc filename | grep "word" 
        done

But I don't know what to write in the last line to compile it.

CodePudding user response:

I think you could do something like this:

for FILE in $(find $foldername -type f -name "*.c"); do
  if grep -q "text here" $FILE; then
    #Compile the file with GCC
  fi
done

I haven't tested it because I'm not on a linux machine right now, and I might have made typo, but at least the logic seems OK.

To compile C, there are two cases:

    1. You compile it "in one go". To do so, simply use
gcc -o output_file_name file1.c

The problem with this technique is that you have to put all the required files in the compilation in one go. For exemple, if file1.c include file2.c, you have to do gcc -o output_file_name file1.c file2.c. In your case, I assume that your files aren't standalone, so that won't work.

    1. You can create object files (.o), and then link them together later. To do so, use the -c flag when compiling: gcc -c file1.c. This will create a file1.o file. Later, when you have created all the required object files, you can link them into a single executable with GCC again
gcc -o output_file_name file1.o file2.o

I have to admit I haven't compiled C "by hand" for a really long time. I used this to remember how it's done https://www.cs.utah.edu/~zachary/isp/tutorials/separate/separate.html. I'm sure there is better tutorials elsewhere, but I simply needed a reminder.

If you can, use automated build tools like make or cmake, even though in you case, because you want to compile only files containing a certain string, it might be complicated.

CodePudding user response:

You are working too hard. If you want to make an executable, you want to use make. It knows the right things to do (eg, it has good default rules). The only hard part is removing the .c suffix. Just do:

find "$directory" -type f -name '*.c' -exec sh -c 'make ${1%.c}' _ {} \;

If you want to specify the compiler, set CC

CC=/my/compiler find "$directory" -type f  -name '*.c' -exec sh -c 'make ${1%.c}' _ {} \;

similarly if you want to set CFLAGS or LDFLAGS, etc. This works even if you have no Makefiles. If you later discover that you need to customize how things are built, you can add a Makefile to record the customizations and this command still works.

  • Related