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[])
where argc
is a count of the program arguments and
argv
is an array of character strings representing the
arguments themselves.
The command line arguments are the whitespace-separated tokens given in the shell command used to invoke the program. For example, if we give the shell the following command:
$myprog left right 'and center'
the program myprog
will start main
with
parameters:
argc: 4 argv: { "myprog", "left", "right", "and center"}Note that the argument count includes the name of the program itself and the
argv
array contains the program name as the first
element, argv[0]
. Because we used quotes in the shell
command, the fourth argument consists of a string containing spaces.
Neil Matthew and Richard Stone, Beginning Linux Programming,
Third Edition,
Wrox, 2004. ISBN 0-7645-4497-7. p 135-141.
Program Arguments (from the GNU C Library Reference Manual).
Maintained by John Loomis, last updated 4 September 2006