Geek Lair

Bash script to compile and run a C program in one step

with 3 comments

Here is a simple script to compile and run a C program:

# Script to compile and execute a c program in one step.

# Get file name without the .c extension
file_name=$(echo $1|sed 's/\(.*\)\.c/\1/')

# Compile the program with -o option to specify the name of the binary
gcc -o $file_name.out $1

# If there were no compilation errors, run the program
if [[ $? -eq 0 ]]; then

The same could be done for C++ programs as well. Just replace the .c in the sed expression with .cpp and replace gcc with g++

Written by anonir

October 26, 2009 at 18:21

Posted in bash, Linux

3 Responses

Subscribe to comments with RSS.

  1. nice. 🙂


    April 29, 2011 at 09:33

    • Could you explain, or link to references ? About ever line ?


      October 29, 2012 at 09:01

  2. Could this be expanded? No demonstration of how it works, no explanation of a bunch of seemingly random characters. Very unhelpful to a beginner.


    April 14, 2016 at 05:36

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: