[英]Access command line arguments in C++
是否可以在不通过int main(int,char **)接收命令行参数的情况下获取命令行参数? 我不想将参数传递给多个方法,因此全局函数将是完美的。 另外,我不想自己通过全局变量存储参数。 我正在运行Windows和Linux。
编辑:示例:
int main()
{
int argc = GetArgumentCount();
char ** argv = GetArguments();
return 0;
}
编辑:可以使用LPTSTR WINAPI GetCommandLine(void); 在Win32中。
https://msdn.microsoft.com/zh-CN/library/ms683156(v=vs.85).aspx
我正在寻找Linux中的等效功能。
是否可以在不通过
int main(int, char**)
接收命令行参数的情况下获取命令行参数?
是的,具有特定于平台的功能。 但这不是必需的(见下文)。
我不想将参数传递给多个方法,
这是可以理解的。 这是一种反模式,也称为“流水数据”。
另外,我不想自己通过全局变量存储参数。
是的,全局变量很少是一个好主意。
这是一种替代方法:将它们作为static
本地容器对象存储在某些全局可用的非成员函数中,该函数通过引用返回容器。
例:
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string>& Arguments()
{
static std::vector<std::string> arguments;
return arguments;
}
void f()
{
// use arguments anywhere else:
std::cout << Arguments()[0];
}
int main(int argc, char* argv[])
{
for (int i = 0; i < argc; ++i)
{
Arguments().push_back(argv[i]);
}
f();
}
当然,这可以变得更加复杂。 例如,您可能希望通过将向量包装在类中并将main
声明为friend
来防止除main
任何人更改向量,如下所示:
#include <iostream>
#include <string>
#include <vector>
class Arguments final
{
public:
static int Count()
{
return arguments.size();
}
static std::string Get(int index)
{
return arguments[index];
};
private:
Arguments() = delete;
friend int main(int argc, char* argv[]);
static std::vector<std::string> arguments;
};
std::vector<std::string> Arguments::arguments;
void f()
{
// use Arguments anywhere else:
std::cout << Arguments::Get(0);
}
int main(int argc, char* argv[])
{
for (int i = 0; i < argc; ++i)
{
Arguments::arguments.push_back(argv[i]);
}
f();
}
请注意,当静态对象被破坏时,需要特别注意避免程序关闭时的错误。 您必须确保没有静态对象的析构函数访问Arguments
,否则您将面临未定义行为的风险。
是否可以在不通过int main(int,char **)接收命令行参数的情况下获取命令行参数?
否(至少不是以可移植的方式 ),但是您可以将通常的argc
, argv
放入某些全局变量(或其他全局数据,通常在解析之后)。 并且这也可能是一些static
数据,而同一 翻译单元中的其他功能则在检索这些数据。 因此,合理的(可读和可移植的)方法将是:
static int myargc;
static char **myargv;
int GetArgumentCount(void) {
return myargc;
}
char**GetArguments(void) {
return myargv;
}
int main(int argc, char**argv) {
myargc= argc;
myargv= argv;
/// etc....
请注意,在某些系统或某些实现中,您可能会通过其他方式访问命令行参数。
例如,在Linux上,使用proc(5)可能会解析/proc/self/cmdline
但是这样做是不合理的(在Linux系统上,尝试在终端上运行od -cx /proc/self/cmdline
来猜猜我的意思),因此我仍然建议使用int main(int argc, char**argv)
并将argc
和argv
存储在某些全局或静态数据中,或者更有可能对程序参数进行一些解析 。
所以在Linux上,你可以编写你的GetArgumentCount
和GetArguments
功能(通过解析/proc/self/cmdline
,另见本 ),但是这将是愚蠢不使用这样做 argc
和argv
从main
(即使它在技术上是可行的)。 对受虐狂的读者GetArgumentCount
, GetArguments
这样一个疯狂的GetArgumentCount
和GetArguments
来解析/proc/self/cmdline
是一种练习。
也许您需要这样做,因为某些静态数据的构造函数- 在 main
之前运行并在crt0中调用它之前-使用了它们; 但在这种情况下,你的程序的设计是恕我直言非常错误的 。 我不知道Windows是否可以使用类似的肮脏技巧。
如果您真的认为这是个好主意,则可以轻松地将cor命令行参数设为全局:
int argc_ = 0;
char** argv_ = NULL;
int main(int argc, char* argv[]) {
argc_ = argc;
argv_ = argv;
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.