The arguments to main
are defined by the C runtime, and the only standard/portable way to obtain the command line arguments. Don't fight the system. :)
If all you want to do is to provide access to command line parameters in other parts of the program with your own API, there are many ways to do so. Just initialise your custom class using argv/argc
in main
and from that point onward you can ignore them and use your own API. The singleton pattern is great for this sort of thing.
To illustrate, one of the most popular C++ frameworks, Qt uses this mechanism:
int main(int argc, char* argv[])
{
QCoreApplication app(argc, argv);
std::cout << app.arguments().at(0) << std::endl;
return app.exec();
}
The arguments are captured by the app and copied into a QStringList
. See QCoreApplication::arguments() for more details.
Similarly, Cocoa on the Mac has a special function which captures the command line arguments and makes them available to the framework:
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **)argv);
}
The arguments are then available anywhere in the app using the NSProcessInfo.arguments property.
I notice in your updated question that your class directly stores a copy of argc/argv
verbatim in its instance:
int const argc_;
char const** const argv_;
While this should be safe (the lifetime of the argv
pointers should be valid for the full lifetime of the process), it is not very C++-like. Consider creating a vector of strings (std::vector<std::string>
) as a container and copy the strings in. Then they can even be safely mutable (if you want!).
I want to make a class that is independent of main() so that argc and argv don't have to be passed explicitly to the code that uses them.
It is not clear why passing this info from main
is somehow a bad thing that is to be avoided. This is just how the major frameworks do it.
I suggest you look at using a singleton to ensure there is only one instance of your Application
class. The arguments can be passed in via main
but no other code need know or care that this is where they came from.
And if you really want to hide the fact that main
's arguments are being passed to your Application
constructor, you can hide them with a macro.
main
. – Freddieargc
andargv
to the "class", take a look at just about all portable and platform-independent GUI frameworks, they all needs the user of the framework to passargc
andargv
to the framework explicitly. So it's common and not something programmers are unused to. – Freddielinux
,windows
,posix
andbsd
and say this question is OS-specific? If it was OS-specific you would mention only one OS, the one you target. – Freddie