Best way to store command line arguments in C
I tend to use either getopt()
or getopt_long
to parse command-line arguments when working with console-based programs. However, most of the time I end up using global variables to store configuration parameters that I can use across all *.c
files.
So I'm interested to know what patterns do you use, and what would be a better alternative to global variables.
I generally define a structure:
struct ConfigurationOpts {
int interval;
int fullscreen;
/* ... */
};
And pass a pointer to an instance of struct ConfigurationOpts
to other modules:
int main() {
struct ConfigurationOpts conf;
/* ... */
init_submodule1(&conf);
init_submodule2(&conf);
return 0;
}
I use a single record to hold all system-wide data, a singleton pattern. Access is through a function returning the value of a static pointer (or macro) to the singleton record. This method allows all kinds of options for expansion, persistence, legacy version compatibility etc. I adopted it after painful experiences with programs that place system-wide data willy-nilly in scattered globals.
Encapsulate
Put all the variable you use globally in a struct.
Keep the scope minimum If only the function that you are calling from main need the cmd-line parameters, then pass the struct with command-line options If it is being called from multiple multiple places, then
hh : Declare+Define global variable which has cmd-line options main.c : Initialize the variable user1.c : Refer the variable via hh user2.c : Refer the variable via hh
(May Not really be applicable in this case.) Just uninitialize the struct with options, after you are done using it. It could really be in middle of your program path or could be at the end. Have a variable that tells if the struct is initialized or not rather than relying on the order of the function calls. (You dont trust interns ! :) )
链接地址: http://www.djcxy.com/p/30426.html上一篇: Python字典理解
下一篇: 在C中存储命令行参数的最佳方法