Recently I've started to learn cpp language on linux,and now I run a cpp file using following commands.
g++ -o xxx xxx.cpp
./xxx
Is there a way to make it one line command such as compile-and-run xxx.cpp
?Thanks.
Jeremy Banks has posted one of the most awesome tricks I've seen in quite some time at SO. Basically, he's adding a single Bash-Script line at the top of the cpp file, which allows him to directly compile and execute that file.
//&>/dev/null;x="${0%.*}";[ ! "$x" -ot "$0" ]||(rm -f "$x";cc -o "$x" "$0")&&exec "$x" "$@"
This explanation is copied from the gist:
//
Since we don't want this visible in C, we put it in a comment.
&>/dev/null
Unfortunately
//
is interpreted as an invalid shell command and produces an error message, so we need to redirect that to/dev/null
to get rid of it.;x="${0%.*}"
This determines what our compiled filename will be by using string replacement to get rid of any extensions on the current filename.
;[ ! "$x" -ot "$0" ]||
This check if there already is a compiled version newer than the source file. If not...
(rm -f "$x";cc -o "$x" "$0")
...we delete any existing version and then compile our code, using our chosen compiled filename.
&&exec "$x" "$@"
If the compile was successful or unnecessary, pass execution to the compiled code, passing on the arguments given to this script.
This technique is called a Polyglot, which means that it is written in multiple languages and can also be interpreted by those language-interpreters without problems.
What about this?
g++ -o xxx xxx.cpp && ./xxx
?
( &&
means it'll wait until the first task is done, &
means it'll start it right after it started the first, you do NOT want this one. )
cplandrun xxx.cpp
..
crun () { g++ -o $1 $1.cpp && ./$1; }
. To use it: crun xxx
.
Jun 24, 2010 at 7:45
Create a Makefile like this:
xxx: xxx.cpp
g++ -o xxx xxx.cpp
run: xxx
./xxx
Then just type make run
. Of course your Makefile can be much more elaborate than that, it's just a simple example. The important thing is the "run" clause.
a simple, generic makefile could do it:
$ cat Makefile
.SUFFIXES: .o .c
.c:
cc -o $@ $<
./$@
$ make myprogram
will compile myprogram.c and will run myprogram. As it is defined with default rules, this works for every .c file in this directory.
Naturally, you must care about libraries, include directories, and other dependencies ...
I hope this helps, nevertheless
you can write a script. like:
#!/bin/bash
g++ -o $1 $1.cpp
./$1
then make it execupable chmod u+x script.sh
and call it like script.sh yourcode
(omit the cpp or alter the script).