views:

3289

answers:

9

I'm writing a library which is to be dynamically loaded in C++.

I'd like to read argc and argv (for debugging reasons) from within my code, however I do not have access to the main function. Is there any way to retrieve the command line (both Windows and Linux solution would be nice).

Thanks, Dan

+11  A: 

There is the GetCommandLine() function in the Win32 API. On other platforms, you would have to save argc/argv somewhere (external variable?).

Martin Cote
+12  A: 

On Linux the pseudo-file /proc/self/cmdline holds the command line for the process. Each argument is terminated with a 0 byte, and the final argument is followed by an additional 0 byte.

Darron
+3  A: 

This thread shows how to do it on Linux.

http://linux.derkeiler.com/Newsgroups/comp.os.linux.development.system/2005-07/0147.html

Bartosz Blimke
+4  A: 

May I suggest that this sounds like a weird situation. Are you writing a plugin or something? Perhaps you should not access argv/argc?

Marcin
I agree. If a library needs access to argv and argc, then the library probably could use a redesign.
Landon
GTK+ needs (or accepts, not sure) argc think "--debug".
aib
argv and argc are passed to GTK+ which is perfectly sensible. What I was referring to - and what DanJ is asking for - was a way for a library to access argv and argc.
Landon
+3  A: 

In Windows you can use GetCommandLine() to get a pointer to the command line and then use CommandLineToArgvW() to convert that pointer to argv[] format. There is only a wide (Unicode) version available, though.

Ferruccio
A: 

Use getpid() and ps command.

int pid;

int fd;

char cmd[80];

pid = getpid();

sprintf(cmd, "ps %d", pid);

fd = popen(cmd, "r");

.... lines should be like

.... 1358 ./a.out abc def

yogman
+1  A: 

On windows you can access argc/argv via __argc and __argv. __wargv if you want the wide character version.

Rhythmic Fistman
+1  A: 
Shadow2531
A: 

Have you given any thought to using environment variables instead of the command line? Might be easier on the user depending on what kinds of applications the library will be used in, and you can use the standard getenv() function.

I think, in any case, if your library is going to use argc and argv, the program should be the one to pass them.

aib