In the C / Unix environment I work in, I see some developers using __progname
instead of argv[0]
for usage messages. Is there some advantage to this? What's the difference between __progname
and argv[0]
. Is it portable?
__progname
isn't standard and therefore not portable, prefer argv[0]
. I suppose __progname
could lookup a string resource to get the name which isn't dependent on the filename you ran it as. But argv[0]
will give you the name they actually ran it as which I would find more useful.
Using __progname
allows you to alter the contents of the argv[]
array while still maintaining the program name. Some of the common tools such as getopt()
modify argv[]
as they process the arguments.
For portability, you can strcopy argv[0]
into your own progname
buffer when your program starts.
I see at least two potential problems with argv[0].
First, argv[0] or argv itself may be NULL if execve() caller was evil or careless enough. Calling execve("foobar", NULL, NULL) is usually an easy and fun way to prove an over confident programmer his code is not sig11-proof.
It must also be noted that argv will not be defined outside of main() while __progname is usually defined as a global variable you can use from within your usage() function or even before main() is called (like non standard GCC constructors).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With