args [0]是否确保是执行的路径? [英] Is args[0] guaranteed to be the path of execution?

查看:112
本文介绍了args [0]是否确保是执行的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个根本的问题,但一个重要的,但是一个重要的...

This is a fundamental question, but an important one none the less...

当启动一个C ++程序的主要方法有以下共同的签名:

int main(int argc, char* args[]) {
    //Magic!
    return 0;
}

是args [0]始终保证是当前正在运行的程序?

推荐答案

它是一个跨平台(因为我在Linux环境中,不总是。这是你通过操作系统给程序的价值。例如,当使用 exec 启动程序时,可以将其设置为任意值:

It is not always. It's the value that you gave the program by the Operation System. For example when starting a program using exec you can set that to an arbitrary value:

int execve(const char *filename, char *const argv[],
           char *const envp[]);

第一个参数是要启动的文件,argv将包含argv [0]为主。 envp包含环境变量(不是由标准C或C ++定义的,这是一个posix的东西)。

The first parameter is the file to start, and argv will contains argv[0] and all other parameters for main. envp contains the environment variables (not defined by Standard C or C++. This is a posix thing).

更精确地说,这是C ++中argv的定义:

More precisely, this is the definition of argv in C++:


实现不应预定义主要功能。此功能不应重载。它应该
具有类型为int的返回类型,否则其类型是实现定义的。所有实现
将允许main的以下定义:

An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:



int main() { /* ... */ }




p>

and



int main(int argc, char* argv[]) { /* ... */ }




在后一种形式中,argc应是传递给程序从
环境中的程序运行程序。如果argc非零,这些参数将在 argv [0] 中通过
argv [argc-1] 作为指向以null结尾的多字节字符串(NTMBS)的初始字符的指针
(17.3.2.1.3.2)和 argv [0] NTMBS的初始字符表示用于调用程序或的
名称。 argc的值应为非负数。
argv [argc] 的值应为0. [注意:建议在
argv后添加任何其他(可选)参数。 ]

In the latter form argc shall be the number of arguments passed to the program from the environment in which the program is run. If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings (NTMBSs) (17.3.2.1.3.2) and argv[0] shall be the pointer to the initial character of a NTMBS that represents the name used to invoke the program or "". The value of argc shall be nonnegative. The value of argv[argc] shall be 0. [Note: it is recommended that any further (optional) parameters be added after argv. ]

这实际上取决于定义一个用于调用程序的名称。如果要获取可执行文件的完整路径,可以使用 GetModuleFileName < a>在Windows上, argv [0] (用于获取用于执行的名称,可能是相对的)以及 getcwd (用于获取当前工作目录,尝试将其命名为绝对路径)。

It's pretty much up to the implementation what defines a "name used to invoke the program". If you want to get the full path of your executable, you can use GetModuleFileName on Windows, and argv[0] (for getting the name used to execute, may be relative) together with getcwd (for getting the current working directory, trying to make the name absolute).

这篇关于args [0]是否确保是执行的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆