Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it compulsory to write int main(int argc, char *argv[]), can't use some other names instead of argc and *argv[]?

I am having some real trouble around here giving command line arguments to Visual Studio in the project options itself (in 'Configuration Properties' -> 'Debugging').

I wrote this "int main(int argc)" after the "int main(int main_i)" did not work. In the MS visual studio property pages' Command line argument for the project I am not sure what I should write. I only want to pass a single integer to designate whether a file is to read or written to thus a mere int argc. I do not need the char *argv[]. I have tried a few values in the command line argument text box but it is not reaching the exe file when it executes, it shows what I did not enter at all.

Could you just provide me with a single simple example of what I need to enter in the MSVS C++ Property Pages' Command Line Argument space? I simply can't find any example on how to give the command line arguments to MSVS.

I also do not understand WHY I need to rebuild the whole project even when I just modified the command line argument value only??

like image 918
quantum231 Avatar asked Jul 15 '12 04:07

quantum231


2 Answers

If you want your program to understand a single integer command line argument, you still have to use argc and argv. Something like this ought to do it:

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

    if (argc < 2) {
        fprintf(stderr, "Need a command line argument.\n");
        exit(1);
    }

    int arg = atoi(argv[1]);
    // now you have an integer
    // do whatever with it...
}

The C standard requires that the main function have specific sets of parameters. One of the allowed combinations is (int, char *[]). You can name the parameters whatever you want, but they're almost always called argc and argv.

like image 77
Greg Hewgill Avatar answered Oct 02 '22 15:10

Greg Hewgill


The names are just a well-established convention, you can use any names you want (though it might raise some eyebrows), however, I have only seen code that has used both arguments in the specified order.

In the pre-ANSI days it was possible to simply have int main(), and it still is .. but these days argc argv are usually supplied.

You can't just supply one of the parameters.

like image 32
Levon Avatar answered Oct 02 '22 14:10

Levon