3

I wrote this .sh file to compile any c source file, so that when I run it, it asks for a filename and gcc compiles it and then, runs the executable a.out.

But this doesn't work properly when error is present in .c files. It also shows that a.out is not present. I don't want this error message ( a.out is not present ) but just want to print only the error message generated for the .c files..

Here's the script..

echo `clear`
echo enter file name
read FILE
gcc $FILE
./a.out
echo -e '\n'
0

5 Answers 5

2

If you enable abort-on-error in shell scripts, life will be a lot easier:

#!/bin/sh
set -eu # makes your program exit on error or unbound variable
# ...your code here...
Sign up to request clarification or add additional context in comments.

Comments

2

Utilizing builtin rules as an alternative to your script you might want to use make as an alternative to a handcrafted script. To compile file.c and run the generated executable all you need to do is:

make file && ./file

If you don't know it, I strongly suggest you take a look at the make utility as it will ease your work a lot. Managing anything more than a one file project can get really nasty without it.

Comments

1

You can chain compilation and execution commands:

echo `clear`
echo enter file name
read FILE
gcc $FILE && ./a.out
echo -e '\n'

Here, if gcc will fail, the shell will drop the ./a.out command.

Comments

1

You may also protect the file name with double quotes :

#! /bin/bash
clear
echo -n "Enter file name: "
read FILE
gcc -Wall -W "$FILE" && ./a.out
echo

1 Comment

Thank you for reminding me of those -Wall -W...I forgot to use them for a while...
0

I there hope this is what you were looking it only requires this command:

./compile executableName myCProgram.c -lm

you can place more C files ahead of each others and add more libraries at the end of the line and executableName does not require the .exe

#!/bin/bash
args="$@"
quant=$#

#Copies in case you need the -lm(math library) params
biblio=${args#*-}
#grabs all params except the first one which should be the name of the executable
firstCommand=${*:2:${#args}}
#Remove the "-lm -lc" from firstCommand
firstCommand=${firstCommand%%-*}

printf "\nEXECUTING: gcc -W -Wall -c $firstCommand\n"

#Creates the object file ".o"
gcc -W -Wall -c $firstCommand

#Convert the files names from example.c to example.o
args=${args//.c/.o}
printf "\nEXECUTING: gcc -o $args\n\n"

#Creates the executable
gcc -o $args

printf "\n**Now execute comand: ./$1  **\n\n"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.