Running C++ code from Command Line
In this article, I want to talk about compiling a C++ program with a help from command line commands. As you know, we generally use the IDE’s for compiling or running our codes, for example Visual Studio, NetBeans, Dev C++ etc.
I would suggest always using IDE’s for writing code lines or generating whole projects. Anyway, I want to start with how to compile C++ code in linux environment.
To compile your c++ code in Linux Command Line
mycode.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.
mycode.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 mycode.cpp or head mycode.cpp (if you need to verify you’re working with the correct “mycode”.)
As noted, 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 mycode.cpp
This will compile mycode.cpp to the binary file named “output”, and you can type ./output to run the compiled code.
To compile your C++ code in Windows Command Line
This is a bit tricky. If you installed a Visual Studio like Visual C++ .NET 2010 Express (even a free one) you can use “cl” command. Run Visual C++ 2010 Express Command Prompt from the start menu, and you can simply compile and run the code.
Here, take a look at the example below:
> cl /EHsc mycode.cpp
If you don’t have any VS in your machine, you can use regular command line.
You can run vcvars32.bat first to set up the environment. Alternatively search for setvcvars.cmd (part of a FLOSS project) and use that to even locate the installed VS and have it call vcvars32.bat for you.