Compiling and running C ++ code with a single command on Linux

My question is simple: is there a way to compile and run C ++ code from a terminal on Linux in one line?

+6
source share
6 answers
g++ myfile.cpp -o myfile && ./myfile 
+9
source

Yes. Assuming your C ++ program is encoded in a single file called foo.cpp:

 g++ foo.cpp -o foo && ./foo 

Note: && means: execute the command on the right only if the command on the left is executed

+5
source

Try this hack:

Paste this line at the top of the cpp file:

 //&>/dev/null;x="${0%.*}";[ ! "$x" -ot "$0" ]||(rm -f "$x";g++ -o "$x" "$0")&&exec "$x" " $@ " 

Then add execute permission in the cpp file, i.e. ( chmod +x foo.cpp ), then:

 ./foo.cpp 
+4
source

This is more of a shell related question than a C ++ question. In most shells, there are many ways to chain commands. Assuming you're using bash (try echo $SHELL to make sure), check out a good bash tutorial .

+2
source

Under "one command," I assume that OP means invoking only one binary from the command line.

In one line: yes; see other answers.

In one command: required - you can use some implicit rules and insert your own run rule through bash here is the line:

 $ ls hello* *ake* ls: cannot access *ake*: No such file or directory hello.c $ cat hello.c #include <stdio.h> int main (int argc, char **argv) { printf("%s %s\n", "hello", "world"); return (0); } $ make hello.run -f - <<< 'hello.run: hello; ./$<' cc hello.c -o hello ./hello hello world $ 
+2
source

In one line: yes; see other answers.

In one team: no.

-2
source

Source: https://habr.com/ru/post/958151/


All Articles