如何在 windows 中更改控制台程序以支持 unicode?

How to change console program for unicode support in windows?

以下程序可以使用msvc或mingw编译。但是mingw版本无法正确显示unicode。为什么?我该如何解决?

代码:

#include <stdio.h>
#include <windows.h>
#include <io.h>
#include <fcntl.h>

int wmain(void)
{
    _setmode(_fileno(stdout), _O_U16TEXT);
    _putws(L"哈哈哈");
    system("pause");

    return 0;
}

Mingw64编译命令:
i686-w64-mingw32-gcc -mconsole -municode play.c

MSVC 编译:

Mingw编译:

编辑:
经过一些测试,问题似乎不是由 mingw 引起的。如果我运行程序直接双击app。 unicode 字符串也无法正确显示。然而,代码页是相同的,437.

原来问题出在控制台字体而不是编译器上。请参阅以下更改控制台字体的演示代码。

发生这种情况是因为缺少 #define UNICODE & #define _UNICODE 。您应该尝试将它与其他 headers 一起添加。 _UNICODE 符号与 headers 一起使用,例如 tchar.h 以将标准 C 函数(例如 printf() 和 fopen())指向 Unicode 版本。

请注意 - 如果使用 Unicode 模式,链接时仍然需要 -municode 选项。

经过一些研究,发现默认的控制台字体不支持 chainese 字形。可以使用 SetCurrentConsoleFontEx 函数更改控制台字体。

演示代码:

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <windows.h>

#define FF_SIMHEI 54

int main(int argc, char const *argv[])
{
    CONSOLE_FONT_INFOEX cfi = {0};

    cfi.cbSize = sizeof(CONSOLE_FONT_INFOEX);
    cfi.nFont = 0;
    cfi.dwFontSize.X = 8;
    cfi.dwFontSize.Y = 16;
    cfi.FontFamily = FF_SIMHEI;
    cfi.FontWeight = FW_NORMAL;
    wcscpy(cfi.FaceName, L"SimHei");

    SetCurrentConsoleFontEx(GetStdHandle(STD_OUTPUT_HANDLE), FALSE, &cfi);

    /* UTF-8 String */
    SetConsoleOutputCP(CP_UTF8); /* Thanks for Eryk Sun's notice: Remove this line if you are using windows 7 or 8 */
    puts(u8"UTF-8你好");

    /* UTF-16 String */
    _setmode(_fileno(stdout), _O_U16TEXT);
    _putws(L"UTF-16你好");

    system("pause");

    return 0;
}