How do I use argc and argv inside a function?

In my program, I have a function to output help/usage info, for the command-line usage, and it calls the function if the user types --help on the CL, but I want it to put in the name of the program as argv[0], but I can't get it to recognize argv in the function (it works fine in main(), but not for functions called in main).

When I compile using gcc I get this:

main.cpp: In function `int main(int, char**)':
main.cpp:37: error: expected primary-expression before "int"
main.cpp:37: error: expected primary-expression before "char"

If I get rid of (int argc, char** argv) from usage(), I get this:

main.cpp: In function `void usage()':
main.cpp:21: error: `argv' was not declared in this scope
main.cpp:21: warning: unused variable 'argv'
main.cpp: In function `int main(int, char**)':
main.cpp:37: error: expected primary-expression before "int"
main.cpp:37: error: expected primary-expression before "char"


It compiles with no probs if I remove argv[0] from the function...

Here is my code (just the important stuff, not the whole program...)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void usage(int argc, char** argv) {
  cout << "Usage: " << argv[0] << " { -d <seconds> | -s | -S } <service>"
       << "\n\n"
       << "Options:\n"
       << "-d, --delay <seconds> \t Delay actions for <s> seconds\n"
       << "-S, --stop <service> \t Stop <service>\n"
       << "-s, --start <service> \t Start <service>\n"
       << "-h, --help \t\t Display this message and exit\n"
       << endl;
}

int main(int argc, char** argv) {
  if (strcmp(argv[1], "--help") == 0) {
    usage();
    exit(0);
  }
}


So, how can I use argv[0] inside a function??

Thanks!
Last edited on
You have to pass it as a parameter.
This is a simple fix so I'll post the code for the fix on line 14.
usage(argc, argv);

You need to pass them as arguments, just as they're passed as arguments to the program.

EDIT: DAMMIT!

-Albatross
Last edited on
I think I tried that...

Wait... I may have tried to declare them while passing them, i.e usage(int agc, char** argv)... Come to think of it, I think I did do that, which, when I think about it, is stupid. Lol... I'll try that out real quick.
Last edited on
YES! It worked!

Thank you very much!

I guess I need to actually learn how functions work! The way I normally learn is I pretty much just dive into it head first, running on guesses and deductions until I run into problems, then I figure out how to fix them. Instead of actually learning how stuff works before diving into it.

On the plus side, I learn very quickly, on the down side, I run into a lotta probs!
Lol.

But, s'all good.
Last edited on
Topic archived. No new replies allowed.