[C++ Study Notes 1] Main function parameter transfer

When running some other open source projects, it often appears that there are parameters after the operation. How is this achieved? How to introduce it in our own projects?

Commonly used forms:

int main(int argc, char* argv[]){
    
     }
int main(int argc, char** argv){
    
     }
int main(int argc, char** argv, char** envp){
    
     }

char** argvRepresents a pointer to a character pointer, which can also be seen as an array of pointers to strings. In C/C++, command-line arguments are passed to the program as strings, so char** argvis used to store command-line arguments.

Here is a sample program that demonstrates how to use char** argvto get command line arguments and output them:

#include <iostream>

int main(int argc, char** argv) {
    
    
    std::cout << "argc = " << argc << std::endl;
    for(int i = 0; i < argc; i++) {
    
    
        std::cout << "argv[" << i << "] = " << argv[i] << std::endl;
    }
    return 0;
}

Run the program and pass some parameters, for example:

./example hello world 123

The output is as follows:

argc = 4
argv[0] = ./example
argv[1] = hello
argv[2] = world
argv[3] = 123

As you can see, char** argvit points to an array of string pointers, each element points to a string, and these strings are command line parameters. The program outputs the value of each parameter in turn by traversing argvthe array.

int main(int argc, char* argv[], char* envp[])Is the main function of the C/C++ program, it contains three parameters:

  1. int argc: Indicates the number of command line parameters, including the program itself. For example, ./example arg1 arg2when the command is executed, argcthe value of 3.

  2. char* argv[]: is a pointer to character pointer to store command line arguments. argv[0]Stores the name of the program, argv[1]stores the first command-line argument, and so on. For example, ./example arg1 arg2when the command is executed, argv[0]the value of is "./example", the value of , is .argv[1]"arg1"argv[2]"arg2"

  3. char* envp[]: is a pointer to character pointer to store environment variables. Each environment variable is a string in the format name=value. For example, envp[0]what is stored is "USER=john", envp[1]what is stored is "HOME=/home/john".

Here is a simple example program that demonstrates how to use these three parameters:

#include <iostream>

int main(int argc, char* argv[], char* envp[]) {
    
    
    std::cout << "argc = " << argc << std::endl;
    for(int i = 0; i < argc; i++) {
    
    
        std::cout << "argv[" << i << "] = " << argv[i] << std::endl;
    }
    for(int i = 0; envp[i] != nullptr; i++) {
    
    
        std::cout << "envp[" << i << "] = " << envp[i] << std::endl;
    }
    return 0;
}

The program can output the values ​​of command-line arguments and environment variables.

Guess you like

Origin blog.csdn.net/kanhao100/article/details/130540200