Параметры функции main (argc, argv)
При создании консольного приложения в языке программирования С++, автоматически создается строка очень похожая на эту:
Эта строка — заголовок главной функции main() , в скобочках объявлены параметры argс и argv. Так вот, если программу запускать через командную строку, то существует возможность передать какую-либо информацию этой программе, для этого и существуют параметры argc и argv[] . Параметр argc имеет тип данных int , и содержит количество параметров, передаваемых в функцию main . Причем argc всегда не меньше 1, даже когда мы не передаем никакой информации, так как первым параметром считается имя функции. Параметр argv[] это массив указателей на строки. Через командную строку можно передать только данные строкового типа. Указатели и строки — это две большие темы, под которые созданы отдельные разделы. Так вот именно через параметр argv[] и передается какая-либо информация. Разработаем программу, которую будем запускать через командную строку Windows, и передавать ей некоторую информацию.
После того как отладили программу, открываем командную строку Windows и перетаскиваем в окно командной строки экзэшник нашей программы, в командной строке отобразится полный путь к программе(но можно прописать путь к программе в ручную), после этого можно нажимать ENTER и программа запустится (см. Рисунок 1).
Рисунок 1 — Параметры функции main
Так как мы просто запустили программу и не передавали ей никаких аргументов, появилось сообщение Not arguments . На рисунке 2 изображён запуск этой же программы через командную строку, но уже с передачей ей аргумента Open .

Рисунок 2 — Параметры функции main
Аргументом является слово Open , как видно из рисунка, это слово появилось на экране. Передавать можно несколько параметров сразу, отделяя их между собой запятой. Если необходимо передать параметр состоящий из нескольких слов, то их необходимо взять в двойные кавычки, и тогда эти слова будут считаться как один параметр. Например, на рисунке изображен запуск программы, с передачей ей аргумента, состоящего из двух слов — It work .

Рисунок 3 — Параметры функции main
А если убрать кавычки. То увидим только слово It . Если не планируется передавать какую-либо информацию при запуске программы, то можно удалить аргументы в функции main() , также можно менять имена данных аргументов. Иногда встречается модификации параметров argc и argv[] , но это все зависит от типа создаваемого приложения или от среды разработки.
Дополнительные статьи
Функция main позволяет получать извне при запуске некоторые значения. Для этого она имеет следующую сигнатуру:
Параметр argc представляет количество аргументов командной строки, которые переданы приложению.
Параметр argv представляет указатель на массив строк, который представляет переданный набор аргументов.
Например, выведем все аргументы из массива argv на консоль:
Если приложению НЕ передается ни одного аргумента, то argc равен 1. А элемент argv[0] представляет имя исполняемого файла. Например, пусть у нас приложение компилируется в файл hello.exe , то при запуске этого файла командой
Значение элемента argv[0] будет равно «hello». Это будет единственный элемент в массиве.
Но передим приложению некоторые аргументы. Например, запустим файл hello.exe с помощью следующей команды:
Тогда программа получит все строки через массив argv и выведет из на консоль:
Name already in use
cpp-docs / docs / cpp / main-function-command-line-args.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
main function and command-line arguments
All C++ programs must have a main function. If you try to compile a C++ program without a main function, the compiler raises an error. (Dynamic-link libraries and static libraries don’t have a main function.) The main function is where your source code begins execution, but before a program enters the main function, all static class members without explicit initializers are set to zero. In Microsoft C++, global static objects are also initialized before entry to main . Several restrictions apply to the main function that don’t apply to any other C++ functions. The main function:
- Can’t be overloaded (see Function overloading).
- Can’t be declared as inline .
- Can’t be declared as static .
- Can’t have its address taken.
- Can’t be called from your program.
The main function signature
The main function doesn’t have a declaration, because it’s built into the language. If it did, the declaration syntax for main would look like this:
If no return value is specified in main , the compiler supplies a return value of zero.
Standard command-line arguments
The arguments for main allow convenient command-line parsing of arguments. The types for argc and argv are defined by the language. The names argc and argv 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 in argv. The argc 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 is argv[argc — 1] , and argv[argc] is always NULL.
For information on how to suppress command-line processing, see Customize 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 using CreateProcess . If you use both the first and second arguments ( lpApplicationName and lpCommandLine ), argv[0] may not be the executable name. You can use GetModuleFileName to retrieve the executable name, and its fully-qualified path.
The following sections describe Microsoft-specific behavior.
The wmain function and _tmain macro
If you design your source code to use Unicode wide characters, you can use the Microsoft-specific wmain entry point, which is the wide-character version of main . Here’s the effective declaration syntax for wmain :
You can also use the Microsoft-specific _tmain , which is a preprocessor macro defined in tchar.h . _tmain resolves to main unless _UNICODE is defined. In that case, _tmain resolves to wmain . 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, see Using generic-text mappings.
Returning void from main
As a Microsoft extension, the main and wmain functions can be declared as returning void (no return value). This extension is also available in some other compilers, but its use isn’t recommended. It’s available for symmetry when main doesn’t return a value.
If you declare main or wmain as returning void , you can’t return an exit code to the parent process or the operating system by using a return statement. To return an exit code when main or wmain is declared as void , you must use the exit function.
The envp command-line argument
The main or wmain 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 name envp 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:
envp
The optional envp 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 to char ( char *envp[] ) or as a pointer to pointers to char ( char **envp ). If your program uses wmain instead of main , use the wchar_t data type instead of char .
The environment block passed to main and wmain is a «frozen» copy of the current environment. If you later change the environment by making a call to putenv or _wputenv , the current environment (as returned by getenv or _wgetenv and the _environ or _wenviron variable) will change, but the block pointed to by envp won’t change. For more information on how to suppress environment processing, see Customize C++ command-line processing. The envp argument is compatible with the C89 standard, but not with C++ standards.
Example arguments to main
The following example shows how to use the argc , argv , and envp arguments to main :
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 the argv[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 the argv 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 the argv 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 in argv .
Example of command-line argument parsing
The following program demonstrates how command-line arguments are passed:
Results of parsing command lines
The following table shows example input and expected output, demonstrating the rules in the preceding list.
| Command-line input | argv[1] | argv[2] | argv[3] |
|---|---|---|---|
| «abc» d e | abc | d | e |
| a\\b d»e f»g h | a\\b | de fg | h |
| a\\\»b c d | a\»b | c | d |
| a\\\\»b c» d e | a\\b c | d | e |
| a»b»» c d | ab» c d |
The Microsoft compiler optionally allows you to use wildcard 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 the argv string array. You can enable wildcard expansion by including the setargv.obj file ( wsetargv.obj file for wmain ) in your /link compiler options or your LINK command line.
For more information on runtime startup linker options, see Link options.
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 the noarg.obj file (for both main and wmain ) in your /link compiler options or your LINK command line.
Similarly, if you never access the environment table through the envp argument, you can suppress the internal environment-processing routine. To suppress its use, include the noenv.obj file (for both main and wmain ) in your /link compiler options or your LINK command line.
Your program might make calls to the spawn or exec 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.
Main function
Every C program coded to run in a hosted execution environment contains the definition (not the prototype) of a function named main , which is the designated start of the program.
| int main (void) <body > | (1) |
| int main ( int argc , char * argv [ ] ) <body > | (2) |
| /* another implementation-defined signature */ (since C99) | (3) |
| argc | — | Non-negative value representing the number of arguments passed to the program from the environment in which the program is run. |
| argv | — | Pointer to the first element of an array of argc + 1 pointers, of which the last one is null and the previous ones, if any, point to strings that represent the arguments passed to the program from the host environment. If argv [ 0 ] is not a null pointer (or, equivalently, if argc > 0), it points to a string that represents the program name, which is empty if the program name is not available from the host environment. |
The names argc and argv stand for «argument count» and «argument vector», and are traditionally used, but other names may be chosen for the parameters, as well as different but equivalent declarations of their type: int main ( int ac, char ** av ) is equally valid.
A common implementation-defined form of main is int main ( int argc, char * argv [ ] , char * envp [ ] ) , where a third argument, of type char ** , pointing at an array of pointers to the execution environment variables, is added.
[edit] Return value
If the return statement is used, the return value is used as the argument to the implicit call to exit() (see below for details). The values zero and EXIT_SUCCESS indicate successful termination, the value EXIT_FAILURE indicates unsuccessful termination.
[edit] Explanation
The main function is called at program startup, after all objects with static storage duration are initialized. It is the designated entry point to a program that is executed in a hosted environment (that is, with an operating system). The name and type of the entry point to any freestanding program (boot loaders, OS kernels, etc) are implementation-defined.
The parameters of the two-parameter form of the main function allow arbitrary multibyte character strings to be passed from the execution environment (these are typically known as command line arguments). The pointers argv[1] .. argv[argc-1] point at the first characters in each of these strings. argv[0] (if non-null) is the pointer to the initial character of a null-terminated multibyte strings that represents the name used to invoke the program itself (or, if this is not supported by the host environment, argv[0][0] is guaranteed to be zero).
If the host environment cannot supply both lowercase and uppercase letters, the command line arguments are converted to lowercase.
The strings are modifiable, and any modifications made persist until program termination, although these modifications do not propagate back to the host environment: they can be used, for example, with strtok .
The size of the array pointed to by argv is at least argc+1 , and the last element, argv[argc] , is guaranteed to be a null pointer.
The main function has several special properties:
If the main function executes a return that specifies no value or, which is the same, reaches the terminating } without executing a return , the termination status returned to the host environment is undefined.