1

我试图使用wmain简单的测试代码来练习 WCS 字符串(而不是 MBCS),但我一直在出错,但无法找出原因。

这是我的代码。

#include <iostream>
#include <stdio.h>

using namespace std;

int wmain(int argc, wchar_t * argv[])
{
    for (int i = 1; i < argc; i++) {
        fputws(argv[i], stdout);
        fputws(L"\n", stdout);
    }

    return 0;
}

它给出了错误信息。

c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../libmingw32.a(main.o):(.text.startup+0xa0): 未定义引用`WinMain@16' collect2.exe:错误:ld 返回 1 个退出状态

为什么会崩溃?我不知道为什么会出现这个错误。

4

1 回答 1

3

wmain是一个 Visual C++ 语言扩展,用于在 Windows 中处理 UTF-16 编码的命令行参数。

但是,现代 MinGW g++(您正在使用的编译器)通过 option 支持它-municode

对于不支持它的编译器,您可以轻松编写几行标准main来调用 Windows'GetCommandLineWCommandLineToArgvW,然后调用一个wmain函数。


main调用的标准示例wmain,如上图所示:

#ifdef USE_STD_MAIN
#include <stdlib.h>         // EXIT_...
#include <windows.h>        // GetCommandLineW, CommandLineToArgvW
#include <memory>           // std::(unique_ptr)
auto main()
    -> int
{
    int n_args;
    wchar_t** p_args = CommandLineToArgvW(GetCommandLineW(), &n_args );
    if( p_args == nullptr )
    {
        return EXIT_FAILURE;
    }
    const auto cleanup = []( wchar_t** p ) { LocalFree( p ); };
    try
    {
        std::unique_ptr<wchar_t*, void(*)(wchar_t**)> u( p_args, cleanup );
        return wmain( n_args, p_args );
    }
    catch( ... )
    {
        throw;
    }
}
#endif

try-catch似乎没有做任何事情的目的是保证调用像u这里这样的局部变量的析构函数是为了调用wmain.

免责声明:我刚刚编写了该代码。它没有经过广泛的测试。

于 2018-09-22T08:27:05.780 回答