Reputation: 45
I've got the main function: main(int argc, char *argv[]). I want to use these variables: argc,argv in other function:
int function()
int main(int argc, char *argv[])
{
...
function();
...
return 0;
}
int function()
{
int b=argc;
return 0;
}
but the compilator give error, that argv is undeclared. How can I use these variables in other functions?
Upvotes: 0
Views: 8103
Reputation: 31545
As you tagged this as C++
too, you can do the following trick:
int argc;
char **argv;
void foo() {
printf("argc: %d\n", argc);
for (int i=0; i < argc; i++)
printf("%s \n", argv[i]);
}
int main(int argc, char **argv)
{
::argc = argc;
::argv = argv;
foo();
return 0;
}
Upvotes: 5
Reputation: 143
Another alternative would be to make two global variables to hold the same values as argc and *argv
Upvotes: 0
Reputation: 852
declare function as
int function (int argc) {
int b = argc;
....
}
call function in main like
function(argc);
OR
use a static variable to store your argc and argv, but this is not recommanded
before you main
int g_argc;
char* g_argv[];
in your main function
g_argc = argc;
g_argv = argv;
function();
int your function just use g_argc directly
Upvotes: 1
Reputation: 310940
argc and argv are local variables of main. You can pass them to other functions as arguments. For example
int function( int );
int main(int argc, char *argv[])
{
...
function( argc );
Upvotes: 2
Reputation: 145829
Pass them as arguments to your functions.
int function(int argc)
{
int b = argc;
return 0;
}
and call
function(argc);
in main
Upvotes: 6