Ubuntu – a command to compile and run C++ programs

ccommand lineprogramming

I am new to Linux. I am using Ubuntu 11.04 and do not know how to compile and execute C++ program in it. I need to know the commands to Compile and Execute a C++ program in Linux.

Best Answer

To compile your c++ code, use:

g++ foo.cpp

foo.cpp in the example is the name of the program to be compiled.

This will produce an executable in the same directory called a.out which you can run by typing this in your terminal:


g++ should already be in your $PATH, so you don't need to call /usr/bin/g++ explicitly, but you can use the latter in any case.

foo.cpp should be in the same directory you're running the command from. If there is any doubt, you can make sure you are in the same directory by typing ls foo.cpp or head foo.cpp (if you need to verify you're working with the correct foo.)

As noted by @con-f-use, the compiler will usually make this file executable, but if not, you can do this yourself (so the command to execute, ./a.out or equivalent, will work):

chmod +x ./a.out

To specify the name of the compiled output file, so that it is not named a.out, use -o with your g++ command.


g++ -o output foo.cpp

This will compile foo.cpp to the binary file named output, and you can type ./output to run the compiled code.