xx - command line arguments

You might have already seen a somewhat different main function:

1
2
3
4
// both are equivalent
// parameter names may be different but these are a very strong convention
int main(int argc, char** argv)
int main(int argc, char* argv[])

This is the way you can define a main function to accept a variable number of null-terminated C-strings, typically called "program's command line arguments".

Command line arguments are one of primary ways to provide input data to the program - you have already seen it with many shell built-in programs (e.g. cd), OS-provided programs (e.g. echo, grep) and others (e.g. compiler, linker).

Details

  • argc is argument count

  • argv is argument vector: an array of C-strings (C-strings are char* so an array of them is char** or char*[])

  • argv[argc] (which normally would be undefined behavior) points to an empty C-string, though I don't see practical value in it (it's the same bad convention as with null-terminated strings, now just for an array)

  • argc >= 0

How exactly the textual arguments are passed to the program is system and implementation dependent (typically spaces separate arguments and quotes must be used to contain them). By the nature of the char type, it's most suitable for ASCII or Unicode UTF-8 and is such in most configurations.

Example

1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main(int argc, char** argv)
{
	std::cout << "argument count: " << argc << "\n";
	std::cout << "argument vector:\n";

	for (int i = 0; i < argc; ++i)
		std::cout << i << ": " << argv[i] << "\n";
}
$ ./program --arg1 --arg2 "a r g 3" -x 10 -y=20
argument count: 5
argument values:
0: ./program
1: --arg1
2: --arg2
3: a r g 3
4: -x
5: 10
6: -y=20

The value behind argv[0] depends on the system. In a typical implementation it will be the same string that has been used to call the program.

Parsing arguments

C++ standard library does not cover argument parsing. I suggest to use any external library instead - many have an API that is easy to understand and allow automatic generation of --help and other commands. Boost has one too but it requires building so unless you already use boost I suggest to find a header-only library (it will be much easier to set up).

In many C projects you may find getopt being used. From C++ point of view its interface is very C-ish but nonetheless it's quite popular in projects for Unix systems.