How to make the main function arguments available to the whole program on pure C ? Maybe there are some libraries for this?

i.e

int main(int argc, char **argv) { myfunc(); } int myfunc() { printf("%d %s", argc, argv[1]); } 

I don't want to do that

 int main(int argc, char **argv) { myfunc(argc, argv); } int myfunc(int argc, char **argv) { printf("%d %s", argc, argv[1]); } 
  • one
    and what prevents global variables from making and simply copying argc and argv into them? - pavel
  • Such an idea was, but maybe there is a more elegant solution? - user206991

3 answers 3

You can create the corresponding global variables and initialize them at the very beginning of the main() function with the arguments passed to it. This is if pure c .

 int Argc; const char ** Argv; void test() { for(int i = 0; i < Argc; ++i) printf("argv[%d] = %s\n",i,Argv[i]); } int main(int argc, const char * argv[]) { Argc = argc; Argv = argv; test(); } 

But it is possible, if you do not approach so strictly the case, to see the documentation on a specific compiler - as a rule, there are some global variables that store these arguments ...

    Parameters obviously must somehow be used. Otherwise, they do not make sense. In order not to reinvent the wheel, I recommend to get acquainted with the library getArgs

       int myfunc(int argc, char **argv) { printf("%d %s", argc, argv[1]); return 0; } int main(int argc, char **argv) { myfunc(argc, argv); return 0; } 
      • How is this different from the TC code? - αλεχολυτ
      • @alexolut, because I did not see it ... Probably opened the question before it was updated and did not update it before answering. In any case, I think that this is the right way to do it. And also, this code will compile, unlike :) - Qwertiy