How to compile C++ code with g++
Before we start you need to have g++ installed on your operating system. g++ is derived from the name gcc. gcc is a compiler for C language. gcc stands for GNU C Compiler. GNU is operating system and also it's a set of free software, including gcc and g++ - compilers for C/C++.
If you are working on Linux there is g++ already on your computer.
g++ for Windows
There is couple options to get g++ on Windows. Cygwin and MinGW32. MinGW also has a version for x86-64 architecture. And that's one we'll use. Download MinGW-W64, install it and then find mingw in the start menu (MinGW-W64 -> Run Terminal) or find where you installed it in explorer (there is file mingw-w64.bat that you need to run). You'll see the Windows command line.
Working with Windows command line
If you never worked with a command line, here is couple commands that you'll need:
Name of the disc with a colon - go to specific disk. For example, I store all my code on disk D so the first command for me will look like:
cd - change directory. This command will move you to a specific directory. I store my code for these tutorials in the folder: d:\prog\cpp. So after I've chosen disk D, I usually enter this command:
cd .. (two dots) will move you to the folder above.
Create file hello_world.cpp in the folder where you plan to store your code. Open it with plain text editor: Notepad/Gedit/Notepad++/Sublime... Paste this text:
This program prints line Hello World in a console. We'll discuss what this code means in next tutorial.
As you can see we store code in plain text files. This is source code. To make it actually work we need to compile it. Now open the folder where you saved the file with source code in command line.
Compile C++ code with g++
New file where created in the current directory: a.out or a.exe. To run the app just print the file name in the console and hit Enter. You'll see text Hello World in the console. After that, your program will immediately stop.
a.out is the default output name of the compiled file. We can change it:
By running the last line I'll receive the file hello_world.exe as output.
Then on Windows you can run your compiled program with the command:
And on Linux:
Compilation and Linking Phases
When we run compiler there are actually two steps. First, compiling of source code files. The result of this step is the so-called object code. New file with extension .o is created. The next step is linking - special program linker takes object file/files and "link" them together. The linker is necessary when there is more than one source code file. We'll return to linker later. For now, all our programs will consist only from one file.
We discussed how to compile C++ source code with g++ compiler. Now we are ready to start learning C++. And we'll start with discussing Hello World.
- Compile hello_world.cpp