流程argc和主要argv的外() [英] Process argc and argv outside of main()

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

问题描述

如果我想保持散装我的code的处理命令行参数出来的主要(用于组织和更具可读性code),这将是做到这一点的最好方法是什么?

 无效的主要(INT ARGC,CHAR *的argv []){
    //很多code在这里,我想迁往别处
}


解决方案

无论是将它们作为参数,或者将它们存储在全局变量。只要你不从主返回并尝试处理它们在 atexit对处理程序或在全局范围内对象的析构函数,它们仍然存在,将是罚款从任何范围的访问。

例如:

  //将它们作为ARGS:
无效process_command_line(INT ARGC,字符** argv的)
{
    //使用argc和argv
    ...
}INT主(INT ARGC,字符** argv的)
{
    process_command_line(ARGC,ARGV);
    ...
}

或者

  //全局变量
INT g_argc;
焦炭** g_argv;无效process_command_line()
{
    //使用g_argc和g_argv
    ...
}INT主(INT ARGC,字符** argv的)
{
    g_argc = ARGC;
    g_argv = argv的;
    process_command_line();
    ...
}

将它们作为参数是一个更好的设计,因为它的封装,并让我们,如果你想修改/替代参数,或者简单地将程序转换成库。全局变量是比较容易的,因为如果你有访问args作为任何原因很多不同的功能,你可以存储它们一次,也不需要保持周围路过他们所有的不同功能之间。

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.

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

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