So I'm in Linux and I want to have a program accept arguments when you execute it from the command line.
For example,
./myprogram 42 -b -s
So then the program would store that number 42 as an int and execute certain parts of code depending on what arguments it gets like -b or -s.
In C, this is done using arguments passed to your
main()
function:More information can be found online such as this Arguments to main article.
Other have hit this one on the head:
main(int argc, char **argv)
give you direct access to the command line (after it has been mangled and tokenized by the shell)getopt()
andgetopt_long()
but as you've seen the code to use them is a bit wordy, and quite idomatic. I generally push it out of view with something like:
Then first thing in main:
Or you could use one of the solutions suggested in Argument-parsing helpers for C/UNIX.
You could use getopt.
Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.
Consider using
getopt_long()
. It allows both short and long options in any combination.Related:
Which command line commands style do you prefer?Instead of
getopt()
, you may also consider usingargp_parse()
(an alternative interface to the same library).From libc manual:
But I was always happy with the standard
getopt
.N.B. GNU
getopt
withgetopt_long
is GNU LGPL.