Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

main function and command-line arguments

  • 2022-02-08
Feedback

In this article

All C++ programs must have amain function. If you try to compile a C++ program without amain function, the compiler raises an error. (Dynamic-link libraries and static libraries don't have amain function.) Themain function is where your source code begins execution, but before a program enters themain function, all static class members without explicit initializers are set to zero. In Microsoft C++, global static objects are also initialized before entry tomain. Several restrictions apply to themain function that don't apply to any other C++ functions. Themain function:

  • Can't be overloaded (seeFunction overloading).
  • Can't be declared asinline.
  • Can't be declared asstatic.
  • Can't have its address taken.
  • Can't be called from your program.

Themain function signature

Themain function doesn't have a declaration, because it's built into the language. If it did, the declaration syntax formain would look like this:

int main();int main(int argc, char *argv[]);

If no return value is specified inmain, the compiler supplies a return value of zero.

Standard command-line arguments

The arguments formain allow convenient command-line parsing of arguments. The types forargc andargv are defined by the language. The namesargc andargv are traditional, but you can name them whatever you like.

The argument definitions are as follows:

argc
An integer that contains the count of arguments that follow inargv. Theargc parameter is always greater than or equal to 1.

argv
An array of null-terminated strings representing command-line arguments entered by the user of the program. By convention,argv[0] is the command with which the program is invoked.argv[1] is the first command-line argument. The last argument from the command line isargv[argc - 1], andargv[argc] is always NULL.

For information on how to suppress command-line processing, seeCustomize C++ command-line processing.

Note

By convention,argv[0] is the filename of the program. However, on Windows it's possible to spawn a process by usingCreateProcess. If you use both the first and second arguments (lpApplicationName andlpCommandLine),argv[0] may not be the executable name. You can useGetModuleFileName to retrieve the executable name, and its fully-qualified path.

Microsoft-specific extensions

The following sections describe Microsoft-specific behavior.

Thewmain function and_tmain macro

If you design your source code to use Unicode wide characters, you can use the Microsoft-specificwmain entry point, which is the wide-character version ofmain. Here's the effective declaration syntax forwmain:

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

You can also use the Microsoft-specific_tmain, which is a preprocessor macro defined intchar.h._tmain resolves tomain unless_UNICODE is defined. In that case,_tmain resolves towmain. The_tmain macro and other macros that begin with_t are useful for code that must build separate versions for both narrow and wide character sets. For more information, seeUsing generic-text mappings.

Returningvoid from main

As a Microsoft extension, themain andwmain functions can be declared as returningvoid (no return value). This extension is also available in some other compilers, but its use isn't recommended. It's available for symmetry whenmain doesn't return a value.

If you declaremain orwmain as returningvoid, you can't return an exit code to the parent process or the operating system by using areturn statement. To return an exit code whenmain orwmain is declared asvoid, you must use theexit function.

Theenvp command-line argument

Themain orwmain signatures allow an optional Microsoft-specific extension for access to environment variables. This extension is also common in other compilers for Windows and UNIX systems. The nameenvp is traditional, but you can name the environment parameter whatever you like. Here are the effective declarations for the argument lists that include the environment parameter:

int main(int argc, char* argv[], char* envp[]);int wmain(int argc, wchar_t* argv[], wchar_t* envp[]);

envp
The optionalenvp parameter is an array of strings representing the variables set in the user's environment. This array is terminated by a NULL entry. It can be declared as an array of pointers tochar (char *envp[]) or as a pointer to pointers tochar (char **envp). If your program useswmain instead ofmain, use thewchar_t data type instead ofchar.

The environment block passed tomain andwmain is a "frozen" copy of the current environment. If you later change the environment by making a call toputenv or_wputenv, the current environment (as returned bygetenv or_wgetenv and the_environ or_wenviron variable) will change, but the block pointed to byenvp won't change. For more information on how to suppress environment processing, seeCustomize C++ command-line processing. Theenvp argument is compatible with the C89 standard, but not with C++ standards.

Example arguments tomain

The following example shows how to use theargc,argv, andenvp arguments tomain:

// argument_definitions.cpp// compile with: /EHsc#include <iostream>#include <string.h>using namespace std;int main( int argc, char *argv[], char *envp[] ){    bool numberLines = false;    // Default is no line numbers.    // If /n is passed to the .exe, display numbered listing    // of environment variables.    if ( (argc == 2) && _stricmp( argv[1], "/n" ) == 0 )         numberLines = true;    // Walk through list of strings until a NULL is encountered.    for ( int i = 0; envp[i] != NULL; ++i )    {        if ( numberLines )            cout << i << ": "; // Prefix with numbers if /n specified        cout << envp[i] << "\n";    }}

Parsing C++ command-line arguments

The command line parsing rules used by Microsoft C/C++ code are Microsoft-specific. The runtime startup code uses these rules when interpreting arguments given on the operating system command line:

  • Arguments are delimited by white space, which is either a space or a tab.

  • The first argument (argv[0]) is treated specially. It represents the program name. Because it must be a valid pathname, parts surrounded by double quote marks (") are allowed. The double quote marks aren't included in theargv[0] output. The parts surrounded by double quote marks prevent interpretation of a space or tab character as the end of the argument. The later rules in this list don't apply.

  • A string surrounded by double quote marks is interpreted as a single argument, which may contain white-space characters. A quoted string can be embedded in an argument. The caret (^) isn't recognized as an escape character or delimiter. Within a quoted string, a pair of double quote marks is interpreted as a single escaped double quote mark. If the command line ends before a closing double quote mark is found, then all the characters read so far are output as the last argument.

  • A double quote mark preceded by a backslash (\") is interpreted as a literal double quote mark (").

  • Backslashes are interpreted literally, unless they immediately precede a double quote mark.

  • If an even number of backslashes is followed by a double quote mark, then one backslash (\) is placed in theargv array for every pair of backslashes (\\), and the double quote mark (") is interpreted as a string delimiter.

  • If an odd number of backslashes is followed by a double quote mark, then one backslash (\) is placed in theargv array for every pair of backslashes (\\). The double quote mark is interpreted as an escape sequence by the remaining backslash, causing a literal double quote mark (") to be placed inargv.

Example of command-line argument parsing

The following program demonstrates how command-line arguments are passed:

// command_line_arguments.cpp// compile with: /EHsc#include <iostream>using namespace std;int main( int argc,      // Number of strings in array argv          char *argv[],   // Array of command-line argument strings          char *envp[] )  // Array of environment variable strings{    int count;    // Display each command-line argument.    cout << "\nCommand-line arguments:\n";    for( count = 0; count < argc; count++ )         cout << "  argv[" << count << "]   "                << argv[count] << "\n";}

Results of parsing command lines

The following table shows example input and expected output, demonstrating the rules in the preceding list.

Command-line inputargv[1]argv[2]argv[3]
"abc" d eabcde
a\\b d"e f"g ha\\bde fgh
a\\\"b c da\"bcd
a\\\\"b c" d ea\\b cde
a"b"" c dab" c d

Wildcard expansion

The Microsoft compiler optionally allows you to usewildcard characters, the question mark (?) and asterisk (*), to specify filename and path arguments on the command line.

Command-line arguments are handled by an internal routine in the runtime startup code, which by default doesn't expand wildcards into separate strings in theargv string array. You can enable wildcard expansion by including thesetargv.obj file (wsetargv.obj file forwmain) in your/link compiler options or yourLINK command line.

For more information on runtime startup linker options, seeLink options.

Customize C++ command-line processing

If your program doesn't take command-line arguments, you can suppress the command-line processing routine to save a small amount of space. To suppress its use, include thenoarg.obj file (for bothmain andwmain) in your/link compiler options or yourLINK command line.

Similarly, if you never access the environment table through theenvp argument, you can suppress the internal environment-processing routine. To suppress its use, include thenoenv.obj file (for bothmain andwmain) in your/link compiler options or yourLINK command line.

Your program might make calls to thespawn orexec family of routines in the C runtime library. If it does, you shouldn't suppress the environment-processing routine, since it's used to pass an environment from the parent process to the child process.

See also

Basic concepts


Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo