views:

238

answers:

4

Is there any way to access the command line arguments, without using the argument to main? I need to access it in another function, and I would prefer not passing it in.

I need a solution that only necessarily works on Mac OS and Linux with GCC.

+1  A: 

You can. Most platforms provide global variables __argc and __argv. But again, I support zneak's comment.

P.S. Use boost::program_options to parse them. Please do not do it any other way in C++.

Pavel Radzivilovsky
Those don't seem to work on Mac OS
Jeffrey Aylesworth
+1  A: 

I do not think you should do it as the C runtime will prepare the arguments and pass it into the main via int argc, char **argv, do not attempt to manipulate the behaviour by hacking it up as it would largely be unportable or possibly undefined behaviour!! Stick to the rules and you will have portability...no other way of doing it other than breaking it...

tommieb75
As the question states, it doesn't need to be portable, only needs to work with GCC (I am only using it in platform specific source files).
Jeffrey Aylesworth
After thinking about it, this would be the best solution.
Jeffrey Aylesworth
+1  A: 

You can copy them into global variables if you want.

florin
A: 

Is there some reason why passing a pointer to space that is already consumed is so bad? You won't be getting any real savings out of eliminating the argument to the function in question and you could set off an interesting display of fireworks. Skirting around main()'s call stack with creative hackery usually ends up in undefined behavior, or reliance on compiler specific behavior. Both are bad for functionality and portability respectively.

Keep in mind the arguments in question are pointers to arguments, they are going to consume space no matter what you do. The convenience of an index of them is as cheap as sizeof(int), I don't see any reason not to use it.

It sounds like you are optimizing rather aggressively and prematurely, or you are stuck with having to add features into code that you really don't want to mess with. In either case, doing things conventionally will save both time and trouble.

Tim Post
I'm not trying to optimize, I'm trying to access command line arguments outside of main.
Jeffrey Aylesworth