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

Jul 10, 2017 at 2:58pm
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 Jul 10, 2017 at 4:35pm
Jul 10, 2017 at 3:06pm
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.
Jul 10, 2017 at 3:20pm
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? :)
Jul 10, 2017 at 6:49pm
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 Jul 10, 2017 at 6:50pm
Jul 10, 2017 at 10:33pm
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 Jul 10, 2017 at 10:34pm
Jul 11, 2017 at 8:33am
Thanks guys! jonnin what you mean? Sorry, I did not understand :)
Jul 11, 2017 at 10:09am
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 Jul 11, 2017 at 10:09am
Jul 11, 2017 at 11:35am
Thanks Peter87!
Jul 11, 2017 at 1:58pm
This thread has been successfully answered, so can be closed :)
Jul 11, 2017 at 3:43pm
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.

Jul 12, 2017 at 12:44pm
Thanks jonnin!
Topic archived. No new replies allowed.