【问题标题】:C++ wmain function error when using Unicode [duplicate]使用Unicode时C ++ wmain函数错误[重复]
【发布时间】:2019-02-26 12:23:57
【问题描述】:

我曾尝试使用 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 个退出状态

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

【问题讨论】:

标签: c++ unicode mingw wmain


【解决方案1】:

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

现代 MinGW g++(您正在使用的编译器)通过选项 -municode 支持它。

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


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

#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

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

【讨论】:

  • 感谢您的回答!祝你有美好的一天:)
猜你喜欢
  • 2014-06-23
  • 1970-01-01
  • 2014-12-17
  • 2021-04-05
  • 2011-04-03
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多