14.3 Using Command-Line Arguments and the MS-DOS Environment

Your application can retrieve the command-line arguments specified when the user started the application; it can also retrieve the current MS-DOS environment.

When a Windows application runs, the Windows startup function copies the command-line arguments to the __argc and __argv variables. Like their counterparts in a standard C application, these variables represent the number of arguments and an array of strings containing the arguments. In addition, the environ variable receives a pointer to an array of strings that contain the current MS-DOS environment at the time the application was started.

To use these variables, you must declare them as external to your application, as follows:

extern int     __argc;
extern char **  __argv;
extern char *  environ[];

You can also retrieve the command-line parameters by parsing the lpszCmdLine parameter, which Windows passes to your application's WinMain function.

If your application does not require access to the command-line arguments or the MS-DOS environment, you can reduce the size of your heap and code by eliminating C run-time initialization code. For information about how to do this, see Section 14.5.10, “Eliminating C Run-Time Startup Code.”

A dynamic-link library (DLL) cannot access the __argc, __argv, and environ variables. Instead, to retrieve the command-line arguments, the library must parse the lpszCmdLine parameter, which Windows passes to the LibEntry function. For more information about LibEntry, see Chapter 20, “Dynamic-Link Libraries.”

Since a dynamic-link library does not have access to the environ variable, it must call the GetDOSEnvironment function to retrieve the environment string.