How to Write a C++ Program With Linux

If you run Linux on your computer, you’re only a few steps away from being able to write, compile, and run C++ programs at the terminal using vim, g++ and gdb. Your system probably already has the vi text editor. However, vim offers many improvements over vi, and is worth installing. Install g++ to compile your code and gdb to debug your code. Type the lines sudo apt-get install vim and sudo apt-get install g++ at the terminal to download and install the necessary programs.

Use the mkdir command to make a new folder for our program, then navigate to that folder with the cd command. Type vi main.cpp to create a new file and start coding. The classic “Hello World” program below demonstrates basic output:

#include 

using namespace std;

int main() {
	cout << "\nThis is a test of the National Broadcasting System." << endl;

	return 0;
}

Because vi is a text-only editor, learning to edit with it can be discouraging for unfamiliar users. Nonetheless, knowing how to use a basic text editor like vi or emacs is an essential survival skill in the computer world. New users should take the time to familiarize themselves with this resource on vi editor commands.

If you aren’t familiar with vi, use the following commands to complete this basic program: Type i to enter insert-mode, and then type the program code listed above. Once you’re done typing the code, press Esc to exit insert-mode. Next press : and type wq to save and quit. Now we’re ready to compile our program by typing the line g++ main.cpp at the terminal.

No news is good news. If the compiler didn’t display any errors, it’s time to run our program by typing ./a.out.

dcampbe@pdx:~/prog1$ g++ main.cpp
dcampbe@pdx:~/prog1$ ./a.out
This is a test of the National Broadcasting System.
dcampbe@pdx:~/prog1$

If your results looked something like the box above, congratulations! You’re officially a computer programmer. The same tools and technique can be used to write programs in the C programming language by replacing the g++ compiler with gcc.