Go to the previous, next section.
The system starts a C program by calling the function main
. It
is up to you to write a function named main
---otherwise, you
won't even be able to link your program without errors.
You can define main
either to take no arguments, or to take two
arguments that represent the command line arguments to the program, like
this:
int main (int argc, char *argv[])
The command line arguments are the whitespace-separated tokens given in
the shell command used to invoke the program; thus, in `cat foo
bar', the arguments are `foo' and `bar'. The only way a
program can look at its command line arguments is via the arguments of
main
. If main
doesn't take arguments, then you cannot get
at the command line.
The value of the argc argument is the number of command line
arguments. The argv argument is a vector of C strings; its
elements are the individual command line argument strings. The file
name of the program being run is also included in the vector as the
first element; the value of argc counts this element. A null
pointer always follows the last element: argv[argc]
is this null pointer.
For the command `cat foo bar', argc is 3 and argv has
three elements, "cat"
, "foo"
and "bar"
.
If the syntax for the command line arguments to your program is simple
enough, you can simply pick the arguments off from argv by hand.
But unless your program takes a fixed number of arguments, or all of the
arguments are interpreted in the same way (as file names, for example),
you are usually better off using getopt
to do the parsing.
Go to the previous, next section.