`main` function and command line arguments (C++) (2023)

  • Article
  • 8 minutes to read

All C++ programs must have aprincipallyOccupation. If you are trying to run a C++ program without aprincipallyfunction, the compiler throws an error. (Dynamic link libraries and static libraries have noprincipallyfunction.) TheprincipallyThe function is where your source code begins execution, but before any program enters theprincipallyThe function will zero out all static class members without explicit initializers. In Microsoft C++, global static objects are also initialized before enteringprincipally. Various restrictions apply to themprincipallyFunction that does not apply to any other C++ function. TheprincipallyOccupation:

  • It cannot be overloaded (cf.function overload).
  • cannot be declared asin line.
  • cannot be declared asstatic.
  • The address cannot be accepted.
  • It cannot be called your program.

Dieprincipallyfunction signature

DieprincipallyThe function has no declaration because it is built into the language. If so, the declaration syntax forprincipallywould be like this:

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

If no return value is specified inprincipally, the compiler will return a value of zero.

Default command line arguments

The arguments forprincipallyallow for convenient parsing of command-line arguments. the guys stopargceargvare defined by the language. The namesargceargvare traditional, but you can name them whatever you like.

Argument definitions are as follows:

argc
An integer containing the count of the following argumentsargv. DieargcThe 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. Agreement,arg[0]is the command with which the program is invoked.argument[1]is the first command line argument. The last command line argument isargv[argc - 1], earg[argc]is always NULL.

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

Use

Agreement,arg[0]is the name of the program file. However, on Windows it is possible to create a processCreateProcess. If you use the first and second arguments (lpApplicationNameelpCommandLine),arg[0]it must not be the name of the executable file. You can useGetModuleFileNameto get the name of the executable and its fully qualified path.

Microsoft specific extensions

The following sections describe Microsoft-specific behavior.

Diewmainfunction and_tmainmacro

If you build your source code to use Unicode wide characters, you can use Microsoft specific codewmainEntrypoint, which is the wide-character version ofprincipally. Here is the effective declaration syntax forwmain:

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

You can also use Microsoft specific_tmain, which is a preprocessor macro defined intchar.h._tmaindecideprincipallyunless_UNICODEIt's defined. In that case,_tmaindecidewmain. Die_tmainMacro and other macros that start with_tare useful for code that needs to create separate versions for narrow and wide character sets. For more information, seeUsing generic text mappings.

ReturnsEmptydo principal

As an extension of Microsoft, theprincipallyewmainFunctions can be declared as returningEmpty(no return value). This extension is also available in some other compilers, but its use is not recommended. It is available for symmetry ifprincipallydoes not return any value.

if you explainprincipallyorwmainas returnEmpty, you cannot return an exit code to the parent process or the operating system using aReturnsExpression. How to return an exit code ifprincipallyorwmainis declared asEmpty, you must use theexitOccupation.

Dieenvpcommand line argument

DieprincipallyorwmainSignatures allow an optional Microsoft-specific extension to access environment variables. This extension is also common in other compilers for Windows and UNIX systems. The nameenvpit's 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 voteenvpParameter is an array of strings representing variables defined in the user's environment. This array is terminated by a NULL input. Can be declared as an array of pointersCharacters(char *envp[]) or as a pointer to pointer toCharacters(char **envp). If your program useswmainrather thanprincipally, Use owchar_tdata type insteadCharacters.

The environment block to pass toprincipallyewmainit is a "frozen" copy of the current environment. If you later change the environment by callingputenvor_wputenv, the current environment (as returned byTenvor_wgetenvit's at_environmentor_wenvironvariable) changes, but the block pointed to byenvpwill not change. For more information on how to suppress environment processing, seeCustomize C++ command line processing. Dieenvpargument is compliant with the C89 standard, but not C++ standards.

examples of arguments tooprincipally

The following example shows how to use theargc,argv, eenvparguments forprincipally:

// argument_definitions.cpp// compile with: /EHsc#include <iostream>#include <string.h>using namespace std;int main( int argc, char *argv[], char *envp[] ){ bool numberLines = INCORRECT; // Default is no line number. // If /n is passed to the .exe, show a numbered list // of the environment variables. if ( (argc == 2) && _stricmp( argv[1], "/n" ) == 0 ) numberLines = true; // Loop through the list of strings until a NULL is encountered. for ( int i = 0; envp[i] != NULL; ++i ) { if ( numberLines ) cout << i << ": "; // Append 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 initialization code uses these rules when interpreting the arguments given on the operating system command line:

  • Arguments are separated by spaces, which are either a space or a tab.

  • The first argument (arg[0]) receives special treatment. Represents the name of the program. As a valid path name must be, the parts are enclosed in double quotes (") They are allowed. Double quotes are not included in thearg[0]Exit. Quoted parts prevent a space or tab character from being interpreted as the end of the argument. Later rules in this list do not apply.

  • A string enclosed in double quotes is interpreted as a single argument, which can contain spaces. A quoted string can be embedded in an argument. The circumflex accent (^) is not recognized as an escape or separator character. Within a quoted string, a pair of double quotes is interpreted as a single escaped double quote. If the command line ends before a closing double quote is encountered, all characters read so far are printed as the last argument.

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

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

  • If an even number of backslashes are followed by double quotes, then a backslash (\) is placed in theargvArray for each pair of backslashes (\\) and double quotes (") is interpreted as a string delimiter.

  • If an odd number of backslashes are followed by double quotes, then a backslash (\) is placed in theargvArray for each pair of backslashes (\\). The double quote is interpreted as an escape sequence by the remaining backslash, resulting in a literal double quote (") insertargv.

Example parsing command-line arguments

The following program demonstrates how to pass command line arguments:

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

Command line analysis results

The following table shows example inputs and expected outputs that illustrate the rules in the previous list.

command line inputargument[1]argument[2]argument[3]
"abc" d.habcde
a\\b d"e f"g ha\\bde fgh
A B C Da\"bcd
a\\\\"b c" d ea\\bcde
A B C DA B C D

wildcard extension

Microsoft compiler allows you to optionally use itplaceholdercharacter, the question mark (?) and asterisk (*) to specify the file name and path arguments on the command line.

Command line arguments are processed by an internal routine in the runtime initialization code, which by default does not expand wildcards into separate stringsargvstring array. You can enable wildcard expansion by including thesetargv.objArchive (wsetargv.objfile forwmain) was behind/Shortcutcompiler options or theirSHORTCUTCommand Line.

For more information about runtime initialization linker options, seelink options.

Customize C++ command line processing

If your program does not accept command-line arguments, you can suppress the command-line handler to save space. To suppress its use, include thenorg.objfile (for bothprincipallyewmain) was behind/Shortcutcompiler options or theirSHORTCUTCommand Line.

Likewise, if you never access through the environment tableenvpargument, you can suppress the inner environment processing routine. To suppress its use, include thenoenv.objfile (for bothprincipallyewmain) was behind/Shortcutcompiler options or theirSHORTCUTCommand Line.

Your program can call thegenerateorexecutiveFamily of routines in the C runtime library. If this is the case, you should not suppress the environment handler as it is used to pass an environment from the parent process to the child process.

See too

basic concept

Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated: 10/27/2022

Views: 6539

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.