DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Introduction to programming in standard C and C++

How C and C++ programs communicate with the shell

Information or control data can be passed to a C or C++ program as an argument on the shell command line. For example, you can invoke the cc command with the names of your source files as arguments:

   $ cc file1.c file2.c file3.c
When you execute either a C or C++ program, command line arguments are made available to the function main in two parameters, an argument count, conventionally called argc, and an argument vector, conventionally called argv. (Every C and C++ program is required to have an entry point named main.) argc is the number of arguments with which the program was invoked. argv is an array of pointers to character strings that contain the arguments, one per string. Because the command name itself is considered to be the first argument, or argv[n], the count is always at least one. Here is the declaration for main:
   int
   main(int argc, char *argv[])
For two examples of how you might use run-time parameters in your program, see ``C and C++ compilation system''.

The shell, which makes arguments available to your program, considers an argument to be any sequence of non-blank characters. Characters enclosed in single quotes ('abc def') or double quotes ("abc def") are passed to the program as one argument even if blanks or tabs are among the characters. You are responsible for error checking and otherwise making sure that the argument received is what your program expects it to be.

In addition to argc and argv, you can use a third argument; envp. envp is an array of pointers to environment variables. See envp(1) exec(2) and environ(5) for more information.

C and C++ programs exit voluntarily, returning control to the operating system, by returning from main or by calling the exit function. A return(n) from main is equivalent to the call exit(n). (Remember that main has type ``function returning int.'')

Your program should return a value to the operating system to say whether it completed successfully or not. The value gets passed to the shell, where it becomes the value of the $? shell variable if you executed your program in the foreground. By convention, a return value of zero denotes success, and a non-zero return value means an error occurred. Use the macros EXIT_SUCCESS and EXIT_FAILURE, defined in the header file stdlib.h, as return values from main or argument values for exit.


Next topic: Other tools
Previous topic: Libraries and header files

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004