问题描述
在 C 或 C++ 应用程序中将参数传递给 main()
时,argv[0]
是否总是可执行文件的名称?或者这只是一个常见的约定,并不能保证在 100% 的情况下都是正确的?
When passing argument to main()
in a C or C++ application, will argv[0]
always be the name of the executable? Or is this just a common convention and not guaranteed to be true 100% of the time?
推荐答案
猜测(甚至是有根据的猜测)很有趣,但您确实需要查看标准文档才能确定.例如,ISO C11 声明(我的重点):
Guesswork (even educated guesswork) is fun but you really need to go to the standards documents to be sure. For example, ISO C11 states (my emphasis):
如果argc
的值大于零,则argv[0]
所指向的字符串代表 程序名称;argv[0][0]
如果程序名在宿主环境中不可用,则应为空字符.
所以不,它只是程序名称,如果该名称可用.而且它代表"程序名称,不一定是程序名称.之前的部分指出:
So no, it's only the program name if that name is available. And it "represents" the program name, not necessarily is the program name. The section before that states:
如果 argc
的值大于零,数组成员 argv[0]
到 argv[argc-1]
包括包含指向字符串的指针,这些字符串在程序启动之前由宿主环境赋予实现定义的值.
这与之前的标准 C99 没有变化,这意味着即使 值 也不是由标准规定的 - 这完全取决于实现.
This is unchanged from C99, the previous standard, and means that even the values are not dictated by the standard - it's up to the implementation entirely.
这意味着如果宿主环境不提供它,程序名称可以为空,如果宿主环境提供,则可以为空,前提是其他任何东西"以某种方式代表程序名称.在我更虐待狂的时刻,我会考虑将它翻译成斯瓦希里语,通过替换密码运行它,然后以相反的字节顺序存储它:-).
This means that the program name can be empty if the host environment doesn't provide it, and anything else if the host environment does provide it, provided that "anything else" somehow represents the program name. In my more sadistic moments, I would consider translating it into Swahili, running it through a substitution cipher then storing it in reverse byte order :-).
然而,实现定义的确实在 ISO 标准中有特定的含义——实现必须记录它是如何工作的.因此,即使是 UNIX,它可以通过 exec
调用系列将它喜欢的任何内容放入 argv[0]
,也必须(并且确实)记录它.
However, implementation-defined does have a specific meaning in the ISO standards - the implementation must document how it works. So even UNIX, which can put anything it likes into argv[0]
with the exec
family of calls, has to (and does) document it.
这篇关于是“argv[0] = 可执行文件名"吗?一个公认的标准还是只是一个共同的约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!