Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create argc argv in the code [duplicate]

Tags:

c++

argv

argc

Hi very newbie question but I just can't figure it out:

I have a function named bar

class foo
{
    public:
        bool bar(int argc, char** argv);
}

argv is supposed to contain

"--dir" and "/some_path/"

How do I create argv and argc so that I can pass them into bar() ? I've tried many ways but I just can't get pointer and type conversion right.

So instead of getting argv from command line, I want to create it in the code.

Thank you for any input!

like image 682
KKsan Avatar asked Oct 05 '16 20:10

KKsan


2 Answers

My favourite way is like this:

std::vector<std::string> arguments = {"--dir", "/some_path"};

std::vector<char*> argv;
for (const auto& arg : arguments)
    argv.push_back((char*)arg.data());
argv.push_back(nullptr);

f.bar(argv.size() - 1, argv.data());

Note, that if arguments are static and do not change, then this is a little bit overkill. But this approach has advantage of being RAII compliant. It manages memory for you and deletes objects at right moment. So if argument list is dynamic, then it is the cleanest way.

Beside that, this code technically is UB if f.bar modifies data in argv array. Usually this is not the case.

like image 107
Alexey Guseynov Avatar answered Nov 15 '22 23:11

Alexey Guseynov


Assuming you want argc and argv in the same format that are passed to main, you can call it like this:

foo f;
char *args[] = {
    (char*)"--dir",
    (char*)"/some_path/",
    NULL
};
f.bar(2, args);

(note: this assumes bar won't modify the argument strings - in which case you should change the argument type to const char ** instead of char **)

like image 28
user253751 Avatar answered Nov 15 '22 23:11

user253751