How to run a c++ program from a command prompt

Hello, I would like to know how to run a c++ program with .cpp extension from command prompt? I know there is a way to run by writing c++ program.cpp -o program.out and then writing ./program.out in the terminal and then the program is run. However, I want to know a simple one command which would allow me to run a program.cpp from terminal prompt straightly? Thank you very much!

P.S. I found such command before, but that was a year ago and now I am returning to program with C++, so unfortunately forgot it.
Last edited on
You can combine the two commands using &&.

 
c++ program.cpp -o program.out && ./program.out


This will first try to compile the program, and if it succeeds it will try to run the program.
Thanks Peter87! But I found before that there was a simple command to run a .cpp program from terminal prompt. Would anyone know of it? :)
Just write one:
function compile-and-run() {
        prog="./${1%*.*}.out"   
        c++ -Wall -Wextra -pedantic-errors -std=c++14 $* -o"$prog" && $prog
}

Usage:
% compile-and-run hello-world.cxx
Hello World!


At a certain point I would suggest using Make, or another build tool.
Last edited on
you can edit your .profile or whatever it is on your shell to default to current folder for commands to avoid the aggravating /folder/a.out command.

once compiled, you can run it all you want just typing
a.out
over and over (a.out is the default name, you can rename it in the compiler or after).


you can get a ton done with a shell script to compile code, for simple programs with just a file or two. At some point, you need make or something.
Last edited on
Thanks guys! jonnin what you mean? Sorry, I did not understand :)
Note that you don't need to retype the command each time. After you have typed it once all you need to do is hit the up key to make it appear again and then press enter to make it run.
Last edited on
Thanks Peter87!
This thread has been successfully answered, so can be closed :)
unix has a weird little file that governs the environment called .profile. If you edit it you can get rid of the need to type the path every time. There are instructions online on what to do and where, its been a while and I don't trust myself to tell you the exact syntax. Its a simple change to a plain text file, just need to check the syntax. Makes life much easier. If I remember, files that start with . are "hidden" sort of to normal ls etc commands but you can force it to show them. Trust me, its there.

Thanks jonnin!
Topic archived. No new replies allowed.