Skip to content

Instantly share code, notes, and snippets.

@nufeng1999
Last active January 27, 2022 14:30
Show Gist options
  • Save nufeng1999/319aaf7693a488821210091c70f6868c to your computer and use it in GitHub Desktop.
Save nufeng1999/319aaf7693a488821210091c70f6868c to your computer and use it in GitHub Desktop.
[GCC 独立于环境msys2 和cygwin的 wprintf 显示不正常,clang 无这种情况] #wprintf

独立于环境msys2 和cygwin的 wprintf 显示不正常
mingw64 mingw-w64-x86_64-gcc 11.2.0-4
/bin/x86_64-w64-mingw32-gcc-11.exe
/bin/x86_64-w64-mingw32-gcc.exe
x86_64-w64-mingw32-clang


基于目标 msys2 和cygwin 环境下的gcc 是正常显示的
msys gcc 11.2.0-2
clang /bin/x86_64-pc-cygwin-gcc-11.exe
/bin/x86_64-pc-cygwin-gcc.exe


WSL2 gcc下 wprintf 显示不正常


WSL2 clang下 wprintf 无这种情况

宽字符转UTF8 不同环境编译执行结果不同
Target: x86_64-linux-gnu

#include <stdio.h>
#include <string.h>
#include <locale.h>
#include <stddef.h>
#include <wchar.h>
int main(void){
setlocale(LC_ALL,"zh_CN.UTF-8");
wprintf (L"%ls \n", L"A wide string");
wprintf (L"%ls \n", L"中文显示");
wprintf (L"%ls \n", L"chinese show 中文显示");
wchar_t* s=L"你好";
wprintf(L"你好c test %ls \n",s);
return 0;
}

由于宽字符的中文 gcc 以gbk方式输出,所以 需要配置输出环境为 gbk,故将
setlocale(LC_ALL,"zh_CN.UTF-8");
改为
setlocale(LC_ALL,"");
编译命令如下
/bin/x86_64-w64-mingw32-gcc.exe src/test.c -o src/test.exe -fexec-charset=gbk
x86_64-w64-mingw32-clang src/test.c -o src/test.exe
wsl2 和 MSYS2 下命令
gcc src/test.c -o src/test.exe -fexec-charset=gbk
这样得到的执行文件在 cmd 和 cygwin 环境下都能正常显示中文
宽字符转GBK看来很成熟和标准

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment