GNU Info

Info Node: (libc.info)Program Arguments

(libc.info)Program Arguments


Next: Environment Variables Up: Program Basics
Enter node , (file) or (file)node

Program Arguments
=================

   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.

   In ISO C 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"'.

   In Unix systems you can define `main' a third way, using three
arguments:

     int main (int ARGC, char *ARGV[], char *ENVP[])

   The first two arguments are just the same.  The third argument ENVP
gives the program's environment; it is the same as the value of
`environ'.  Note: Environment Variables.  POSIX.1 does not allow this
three-argument form, so to be portable it is best to write `main' to
take two arguments, and use the value of `environ'.

Argument Syntax
By convention, options start with a hyphen.
Parsing Program Arguments
Ways to parse program options and arguments.

automatically generated by info2www version 1.2.2.9