20

I have a program that can accept command-line arguments and I want to access the arguments, entered by the user, from a function. How can I pass the *argv[], from int main( int argc, char *argv[]) to that function ? I'm kind of new to the concept of pointers and *argv[] looks a bit too complex for me to work this out on my own.

The idea is to leave my main as clean as possible by moving all the work, that I want to do with the arguments, to a library file. I already know what I have to do with those arguments when I manage to get hold of them outside the main. I just don't know how to get them there.

I am using GCC. Thanks in advance.

Eternal_Light
  • 676
  • 1
  • 7
  • 21

3 Answers3

34

Just write a function such as

void parse_cmdline(int argc, char *argv[])
{
    // whatever you want
}

and call that in main as parse_cmdline(argc, argv). No magic involved.

In fact, you don't really need to pass argc, since the final member of argv is guaranteed to be a null pointer. But since you have argc, you might as well pass it.

If the function need not know about the program name, you can also decide to call it as

parse_cmdline(argc - 1, argv + 1);
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • 4
    What about when argv is defined as const char *argv[]? That's how OS X is, and I can't exactly change Apple's ABI... – MarcusJ Jun 04 '16 at 11:24
  • 1
    @MarcusJ Yeah -- ARC does get in the way of that in XCode on OSX. I had to pass them to my ObjC++ class method like `getParams(argc,argv)`, but then had to declare that function like `static std::map getParams(int argc, const char **argv)` Note the `**argv`. Then, inside the class method, I could use `argv` as normal as if it were in the `main` function. (The `map` stuff on the return result was because my function converted the variables into key=value map pairs. Not that you might do that also.) – Volomike Jul 18 '16 at 00:34
2
SomeResultType ParseArgs( size_t count, char**  args ) {
    // parse 'em
}

Or...

SomeResultType ParseArgs( size_t count, char*  args[] ) {
    // parse 'em
}

And then...

int main( int size_t argc, char* argv[] ) {
    ParseArgs( argv );
}
Ed S.
  • 122,712
  • 22
  • 185
  • 265
1

Just pass argc and argv to your function.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547