# Parsing Argument Using Getopt in C/C++

## Introduction

In Python, because of the official standard library argparse and the dynamic typing nature, it is relatively easy to implement arguments of different types and kinds for programs. In C/C++, however, there is no official standard library for parsing arguments. While there are a good number of the argument parser libraries implemented from the third party, GNU’s getopt and argp, Boost’s program_options, and Google’s gflags seems to be the best candidates people should consider because they are open source and have a large community to develop and maintain.

GNU’s getopt actually consists of two commonly used functions getopt and getopt_long. getopt follows POSIX standard, but getopt_long does not follow any standard at all. getopt should be portable across all Linux systems since it follows POSIX standard. However, both getopt and getopt_long would not work on a Windows system.

In this blog post, I am going to give a shot to GNU’s getopt and getopt_long.

## GNU’s Getopt

getopt only works with single character options. That is to say, if you want to use an option, such as learning-rate, getopt is not what you are looking for. The description for the options argument for getopt on the official documentation was confusing to me. It turns out that the option without : and the option with :: are all options for toggling rather than optional arguments, although you could still provide arguments for these options.

### Example

We compiled the program using the following command.

We ran some tests.

### Caveats

To use it unambiguously, I think we should never give an argument to the toggle options which are not followed by : or followed by ::.

## GNU’s Getopt_Long

getopt_long extended the functionality of getopt to use long options, which is good. struct option allows the user to arrange options together more clearly.

### Example

We compiled the program using the following command.

We ran some tests.

### Caveats

In order to avoid ambiguity, one needs to manually check the consistency of the argument requirements for the single character options and long options.

## Conclusions

getopt is almost useless for high-level applications in my opinion. While getopt_long might look to be suitable for different kind of argument parsing tasks, both getopt and getopt_long does not generate help instructions automatically. In addition, there is no automatic type casting for the arguments. These are lethal to many application developments.

## References

Parsing Argument Using Getopt in C/C++

https://leimao.github.io/blog/Argument-Parser-Getopt-C/

Lei Mao

12-24-2019

12-24-2019