在 main() 之外处理 argc 和 argv [英] Process argc and argv outside of main()

查看:27
本文介绍了在 main() 之外处理 argc 和 argv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想将处理命令行参数的大部分代码保留在 main 之外(为了组织和更易读的代码),最好的方法是什么?

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
}

推荐答案

要么将它们作为参数传递,要么将它们存储在全局变量中.只要您不从 main 返回并尝试在 atexit 处理程序或全局范围内的对象的析构函数中处理它们,它们仍然存在并且可以从任何范围访问.

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.

例如:

// 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);
    ...
}

或者:

// 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();
    ...
}

将它们作为参数传递是一种更好的设计,因为它是封装的,如果需要,您可以修改/替换参数,或者轻松地将程序转换为库.全局变量更容易,因为如果您有许多不同的函数,无论出于何种原因访问 args,您只需将它们存储一次,而无需在所有不同的函数之间不断传递它们.

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.

这篇关于在 main() 之外处理 argc 和 argv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆