Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Access to command line arguments outside main?

I have a couple command line apps that both end up calling into com objects. Rather than adding new interface to these com objects, can they access the parameters passed from the command line?

Edit: Sort of how I can call GetModuleFileName to get the file name. Im wondering if there is an equivalent method to get the args.

like image 617
Kyle Avatar asked Nov 16 '09 18:11

Kyle


People also ask

How do you pass command line arguments in C?

To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.

Can you use argv outside of main?

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.

Can you pass command line arguments?

It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code.

How do I get to command line arguments?

Go to the Shortcut tab, then locate the Target field, which lists the exact location of the file within quotation marks. In the Target text box, place the cursor after the last quotation mark, then add a blank space followed by the command line parameters. All command line parameters are preceded with a hyphen (-).


3 Answers

The Win32 API that you're looking for is: GetCommandLine.

Your COM object probably needs to run within your process though.

To convert the command line to an argv style array of strings, call the CommandLineToArgvW function.

like image 170
Brian R. Bondy Avatar answered Oct 31 '22 01:10

Brian R. Bondy


That's platform specific.

In Win32 you can use GetCommandLine().

You will have to do the parsing manually, though.

like image 39
EFraim Avatar answered Oct 31 '22 01:10

EFraim


In Windows you can get the command line with a WIN32 function (GetCommandLine) call but it won't be parsed into an array like argc/argv. If the COM object uses MFC you can get the command line arguments from your CWinApp object. Otherwise, there's no easy way to do it.

like image 1
jmucchiello Avatar answered Oct 31 '22 02:10

jmucchiello