Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag.
In C, we don’t have a built-in flag parsing package like Go’s flag package. Instead, we’ll implement basic command-line flag parsing manually using the argc and argv parameters of the main function.
We declare variables for each flag with default values. Then, we iterate through the command-line arguments to parse the flags and update the variables accordingly.
The program supports the following flags:
-word: a string flag with default value “foo”
-numb: an integer flag with default value 42
-fork: a boolean flag
-svar: a string flag with default value “bar”
We also implement a basic help text functionality with -h or --help flags.
To compile and run the program:
Note that if you omit flags, they automatically take their default values:
Trailing positional arguments can be provided after any flags:
Use -h or --help flags to get the help text for the command-line program:
If you provide a flag that wasn’t specified, the program will print an error message and show the help text:
This C implementation provides similar functionality to the original example, with basic command-line flag parsing and usage information.