I want to call snmpget.c
from another c program in the same project. For that reason I have changed the main()
into a function say get_func()
which takes the same arguments. But i an not sure how to give the arguments namely argv[0]
My arguments look something like this:
char *argstr[]=
{
"v",
"1",
"c",
"public",
"-Ovq",
"192.168.1.1",
"ifInOctets.7",
"ifOutOctets.7",
NULL
};
And then
i = get_func(10, argstr);
1.Should argv[0]
be the app name or path?
2.Is using char *argstr[]
correct for c?
3.snmpget
is not taking these arguments correctly. What could the reason be?
It works correctly with the same args in command.
get_func
expects the arguments starting at argv[1]
, so your argstr
argument should not start with "v"
but with something else (e.g. the programme name or just an empty string if get_func
doesn’t use it).Yes. But be aware that your argstr
contains non-modifiable strings, if get_func
wants to modify them, you can use compound literals
char *argstr[]= { (char []){ "v" }, (char []){ "1" }, /* etc */ NULL };
See 1. and 2. Additionally, argc
is incorrect (must be sizeof argstr/sizeof *argstr - 1
, which is 8 in your case, not 10).
Not directly an answer to your question, but consider redesigning this (depends on what exactly you’re currently doing, however). For example, write a function accepting a structure where the different options are stored (already parsed and validated) and change the old main
from snmpget.c to a function only scanning and validating arguments, initializing such a structure object, and calling this function. And then, perhaps split your files into snmpget.c, snmpget_main.c, another_c_file.c (with better names, of course) and link both user interface implementations against the object file of snmpget.c.