Monday, August 24, 2015

C++ Command Line Args - Hello World

To start off this blog I'm going to begin with a simple hello world program. I was questioned about command line arguments by a friend. So here's killing two birds with one stone.

A little bit about command line arguments, what are they? Command line arguments are additional strings that you can append to a command when running an application from the command line. These additional segments of information get passed to the application when executed. The program will then decide what to do with the extra data provided. If you've ever used a command line tool like ls, then you might know that you can change its behavior with command line arguments. Here is an example of this:
You can see adding -l and -lh provide the user with a more detailed output.

The example that I have written below takes any number of command line arguments and will output to you how it has interpreted each argument. This example is a good starting point to begin learning how to handle the arguments for an application of your choosing.

Big thanks to gist-it for providing an embedding service for github code. The following instructions were executed on a distribution of Linux. There can be much more information associated with getting a compiler and running it, but here are the basics: Copy the code into a text editor of your choice and save it as a .cpp file. From the command line you can use the g++ compiler to create an executable. Once compiled you can run the application and pass in some command line arguments. Here is a simple example of this process:
Feel Free to post any question you might have, I'm more than happy to get you pointed in the right direction, cheers!