Introduction
In this installment, we will look at parsing command-line options. We’re going to use Jon Pryor‘s NDesk.Options library. Since he has not made a .deb package yet, we’ll use curl to integrate NDesk.Options.cs into our codebase.
Get back to our workspace
$ cd ~/src/greeting
Get curl
$ sudo apt-get install curl
Pull down a copy of NDesk.Options
$ curl "http://git.ndesk.org/?p=ndesk-options;a=blob_plain;f=src/NDesk.Options/NDesk.Options/Options.cs;hb=c52aa20569b49b620deb0fd28b19909b7c577d47" > NDesk.Options.cs
Update our Makefile
Updates are bolded below.
$ cat > Makefile
# the first target is the one executed when no target is named
all: Greeting.exe
#don't do anything
# running 'make clean' will execute this target
clean:
rm Greeting.exe
# running 'make Greeting.exe' will execute this target
Greeting.exe: Greeting.cs NDesk.Options.cs
# the same as gmcs -out:Greeting.exe Greeting.cs NDesk.Options.cs
gmcs -out:$@ $^
Update our C# code
Updates are bolded below.
$ cat > Greeting.cs
using System; // This brings in Console.Writeline, used below
using NDesk.Options; // This brings in the options parser used below
class Greeting {
private static string [] planet =
{ "World", "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto" };
// This is the program entry point
public static int Main( string [] argv ){
// default to "World"
int planetNum = 0;
// set up an option parser
var p = new OptionSet () {
{ "n|number=", "The planet number to greet",
(int v) => planetNum = (v < planet.Length ? v : 0) }
};
p.Parse (argv);
// A simple operation to confirm that our app is running:
Console.WriteLine("Greetings, {0}!", planet[planetNum]);
// Well-behaved software returns an int from Main
return 0;
}
}
Compile
$ make
Run it a few times
$ ./Greeting.exe
Greetings, World!
$ ./Greeting.exe –n 1
Greetings, Mercury!
$ ./Greeting.exe ––number 2
Greetings, Venus!
$ ./Greeting.exe ––number 10
Greetings, World!
$ ./Greeting.exe –n 99
Greetings, World!
Summary
That about wraps up sending command line arguments to the application. Thanks to Jon for providing support for NDesk on #mono. You’re right. I should read your docs instead of bothering you!
We now have a bit more complication in our build system and have something we can re-factor a bit. In the next article, we’ll start to make use of some of the autotools bits.