We know that every C program must have a special function, main(). We have also always defined our driver, main(), as:
main()
{ ...
as if it had no parameters or return value. But we also know that commands like the C compiler, cc, are just C programs. When we run them, we can say things like:
% cc driver.c -o program
Well, main() really does have parameters and a return value. The real prototype for main looks like:
int main(int argc, char *argv[]);
The return value is an integer called the status code. This value can be used by the shell to indicate whether the program terminated normally, or something went wrong. The convention in Unix is that a 0 status code means everything is ok, and a non-zero value means something went wrong.
The parameters to main() are the command line arguments passed to the program from the shell. argc indicates how many arugments there were on the line. argv is an array of character pointers. Each of those character pointers points to a string, one per command line argument.
NOTE:
argv is NOT an array of strings (2D array of characters). It is and array of pointers to arrays of characters:
argv[0] is the string used to invoke the command itself. argv[1] is the string corresponding to the first argument, argv[2] is the string corresponding to the second argument, etc. After the last arguement on the command line, the pointer in argv[] is set to NULL.
So we could modify the driver to the stock program as:
int main(int argc, char *argv[])
cc args.c -o args
int main(int argc, char *argv[]){
for ( int i = 0; i< argc; i++)
printf("%s\n", argv[i]);
}
On the command line
./args d -f hello
the output will look like this
d
-f
hello