If I want to keep the bulk of my code for processing command line arguments out of main (for organization and more readable code), what would be the best way to do it?
void main(int argc, char* argv[]){
//lots of code here I would like to move elsewhere
}
Either pass them as parameters, or store them in global variables. As long as you don't return from main and try to process them in an atexit
handler or the destructor of an object at global scope, they still exist and will be fine to access from any scope.
For example:
// Passing them as args:
void process_command_line(int argc, char **argv)
{
// Use argc and argv
...
}
int main(int argc, char **argv)
{
process_command_line(argc, argv);
...
}
Alternatively:
// Global variables
int g_argc;
char **g_argv;
void process_command_line()
{
// Use g_argc and g_argv
...
}
int main(int argc, char **argv)
{
g_argc = argc;
g_argv = argv;
process_command_line();
...
}
Passing them as parameters is a better design, since it's encapsulated and let's you modify/substitute parameters if you want or easily convert your program into a library. Global variables are easier, since if you have many different functions which access the args for whatever reason, you can just store them once and don't need to keep passing them around between all of the different functions.