First Time To Run C++ Program on Ubuntu 14.04

Solution 1:

First you need to compile and link your program. Assuming the source code is saved in a file yourprog.cpp, you can do that using the GNU C++ compiler g++, for example

g++ -Wall -o yourprog yourprog.cpp

The resulting executable will be called yourprog and you can then run it using

./yourprog

Solution 2:

Here's a way to use make to build and run your program without requiring any additional setup:

make CXXFLAGS='-Wall -Werror' hello_world && ./hello_world

But assuming you will continue developing, you will want to create a file called Makefile to streamline things further.

CXXFLAGS = -Wall -Werror
default: build
build: hello_world
run: build
<tab>./hello_world

Then you can build and run your program by typing:

make run

If you just want to see if your program compiles without error, type:

make

Other notes:

  • The <tab> above should be created using the tab key.
  • It is important to include -Wall -Werror. These flags prevent certain obvious programming bugs from being ignored by the compiler. That means less debugging work for the programmer.
  • I advocate the use of the -s option with make. It eliminates (usually) unnecessary verbosity.
  • One feature of make is that it doesn't recompile your program if it doesn't need to. This can be a nice time-saver if the program takes a long time to compile. This is especially useful if your project has more than one source (.cpp) file, since these can be compiled independently -- and even in parallel (simultaneously) with the -j option.