Search code examples
c++compiler-flags

C++ program flags


I write a program in C++, and the complier is G++

Now in the terminal, if I type ./main and enter it will run.

Yet I want to add something like a flag: ./main -apple or ./main -orange

apple and orange are two different methods to calculate one same problem. How do I make it?

I mean, when we do linux stuff, we usually can type dash sth, how does this work and what should I do in my program?

Any example or link?

Thanks in advance!


Solution

  • int main(int argc, const char* argv[]) {
        for(int i = 0; i < argc; ++i) {
            // argv[i] contains your argument(s)
        }
    }
    

    Some more details:

    Accepting arguments passed to your program can be done by adding two arguments to main: One int, which is assigned the number of arguments you give to your program, and one const char* [], which is an array of C strings.

    One example: Say you have a program main which should react to the arguments apple and orange. A call could look like this: ./main apple orange. argc will be 3 (counting "main", "apple", and "orange"), and iterating through the array will yield the 3 strings.

    // executed from terminal via "./main apple orange"
    #include <string>
    int main(int argc, const char* argv[]) {
        // argc will be 3
        // so the loop iterates 3 times
        for(int i = 0; i < argc; ++i) {
    
            if(std::string(argc[i]) == "apple") {
                // on second iteration argc[i] is "apple" 
                eatApple();
            }
    
            else if(std::string(argc[i]) == "orange") {
                // on third iteration argc[i] is "orange" 
                squeezeOrange();
            }
    
            else { 
                // on first iteration argc[i] (which is then argc[0]) will contain "main"
                // so do nothing
            }
        }
    }
    

    This way you can perform tasks according to the application arguments, if you only want to squeeze an orange, just give one argument, like ./main orange.