How to compile and run C/C++ in a Unix console/Mac terminal?
If it is a simple single source program:
make foo
where the source file is foo.c or foo.cpp, etc.
You dont even need a makefile. Make has enough built-in rules to build your source file into an executable of the same name, minus extension.
Running the executable just built is the same as running any program - but you will most often need to specify the path to the executable as the shell will only search what is in $PATH
to find executables, and most often that does not include the current directory (.
).
So to run the built executable foo
:
./foo
gcc main.cpp -o main.out
./main.out
This is the command that works on all Unix machines... I use it on Linux/Ubuntu, but it works in OS X as well. Type the following command in Terminal.app.
$ g++ -o lab21 iterative.cpp
-o
is the letter O not zero
lab21
will be your executable file
iterative.cpp
is your c++ file
After you run that command type the following in terminal to run your program:
$ ./lab21