问题描述
如果我使用以下 main() 方法运行我的 C++ 应用程序,一切正常:
If I run my C++ application with the following main() method everything is OK:
int main(int argc, char *argv[])
{
cout << "There are " << argc << " arguments:" << endl;
// Loop through each argument and print its number and value
for (int i=0; i<argc; i++)
cout << i << " " << argv[i] << endl;
return 0;
}
我得到了我的期望并且我的论点被打印出来了.
I get what I expect and my arguments are printed out.
但是,如果我使用 _tmain:
However, if I use _tmain:
int _tmain(int argc, char *argv[])
{
cout << "There are " << argc << " arguments:" << endl;
// Loop through each argument and print its number and value
for (int i=0; i<argc; i++)
cout << i << " " << argv[i] << endl;
return 0;
}
它只显示每个参数的第一个字符.
It just displays the first character of each argument.
造成这种情况的区别是什么?
What is the difference causing this?
推荐答案
_tmain
在 C++ 中不存在.main
会.
_tmain
does not exist in C++. main
does.
_tmain
是 Microsoft 扩展.
_tmain
is a Microsoft extension.
main
根据 C++ 标准,是程序的入口点.它具有以下两个签名之一:
main
is, according to the C++ standard, the program's entry point.
It has one of these two signatures:
int main();
int main(int argc, char* argv[]);
Microsoft 添加了一个 wmain,将第二个签名替换为:
Microsoft has added a wmain which replaces the second signature with this:
int wmain(int argc, wchar_t* argv[]);
然后,为了更容易在 Unicode (UTF-16) 和它们的多字节字符集之间切换,他们定义了 _tmain
,如果启用了 Unicode,则将其编译为 wmain
,否则为 main
.
And then, to make it easier to switch between Unicode (UTF-16) and their multibyte character set, they've defined _tmain
which, if Unicode is enabled, is compiled as wmain
, and otherwise as main
.
至于你问题的第二部分,谜题的第一部分是你的主要功能是错误的.wmain
应该采用 wchar_t
参数,而不是 char
.由于编译器不会对 main
函数强制执行此操作,因此您会得到一个程序,其中将 wchar_t
字符串数组传递给 main
函数,它将它们解释为 char
字符串.
As for the second part of your question, the first part of the puzzle is that your main function is wrong. wmain
should take a wchar_t
argument, not char
. Since the compiler doesn't enforce this for the main
function, you get a program where an array of wchar_t
strings are passed to the main
function, which interprets them as char
strings.
现在,在启用 Unicode 时 Windows 使用的字符集 UTF-16 中,所有 ASCII 字符都表示为字节对