Arguments to main()

From Appmethod Topics
Jump to: navigation, search

Go Up to The main() Function Index

Three parameters (arguments) are passed to main by the Appmethod C++ startup routine: argc, argv, and env.

  • argc, an integer, is the number of command-line arguments passed to main, including the name of the executable itself.
  • argv is an array of pointers to strings (char *[]).
    • argv[0] is the full path name of the program being run.
    • argv[1] points to the first string typed on the operating system command line after the program name.
    • argv[2] points to the second string typed after the program name.
    • argv[argc-1] points to the last argument passed to main.
    • argv[argc] contains NULL.
  • env is also an array of pointers to strings. Each element of env[] holds a string of the form ENVVAR=value.
    • ENVVAR is the name of an environment variable, such as PATH.
    • value is the value to which ENVVAR is set, such as C:\APPS;C:\TOOLS; (for PATH).

If you declare any of these parameters, you must declare them exactly in the order given: argc, argv, env. For example, the following are all valid declarations of arguments to main:

int main()
int main(int argc)         /* legal but very unlikely */
int main(int argc, char *argv[])
int main(int argc, char *argv[], char *env[])]

The declaration int main(int argc) is legal, but it is very unlikely that you would use argc in your program without also using the elements of argv.

The argument env is also available through the global variable _environ.

For all platforms, argc and argv are also available via the global variables _argc and _argv.

Using main() with a Unicode application

The Unicode version of the main function is:

int wmain (int argc, wchar_t *argv[], wchar_t *env[])

The argv (and optional envp) parameter(s) support(s) wide-characters.

The following _tmain function is a macro that expands to the appropriate version of the main function depending upon the type of application:

int _tmain (int argc, _TCHAR *argv[], _TCHAR *env[])

See Also