Now that you know how to use the command line, it’s time to use the
g++ compiler. (We'll be using the C++ language.)
For Windows users, we have to take a short detour to install it first. Please go to https://wiki.wxwidgets.org/Installing_MinGW_under_Windows. Make sure you add
C:\MinGW\bin to your
Path environment variable. There are instructions on the link.
For OSX users, you have to install Xcode then download the command line tools from there.
For Linux users, it comes free! Nothing to do here.
Now that you’re all done setting up, it’s time to start compiling! If you save your source code file as
source.cpp, you can compile it using the command
g++ source.cpp. By default it saves the resulting executable as
On Windows, the default name of the executable is
a.exe. You can change the name for the resulting output file by adding
-o filename to the command. For example, if my source code is
example.cpp and I wanted to save the output executable as
executable I should then type the command
g++ example.cpp -o executable. Note that for Windows users, the resulting executable name should end with
.exe otherwise Windows won’t run it.
We recommend that you try compiling a sample Hello World program this way before moving on.
Now that you’ve compiled your program, it’s time to run it! For Linux and OSX users, the command to run a program is
./program_name. So if your program is saved as
a.out, you should type
./a.out, and if it’s saved as
executable, you should type
./executable. For Windows users, you don’t even need the
./. So if your program is saved as
a.exe, just type
a.exe directly and it should run.
We recommend that you try running the code you compiled earlier before moving on.
In case you accidentally run code that never ends or you just want it to die for some other reason, what can you do? It’s gonna block your command line and stop you from typing other commands, so you will want to kill it. You can opt to kill it using the task manager, but there's a much easier way. Just press
Control + C. This will work on any operating system and will kill the program that’s hogging up the command line.
We recommend you write a program with an infinite loop, compile it, run it, then kill it just to try out
Control + C.