`wide-exec-charset`不会改变`wchar_t`的字符集

问题描述

这是简单的C ++代码

#include <iostream>
#include <locale>

int main() {
    std::wcout.sync_with_stdio(false);
    std::wcout.imbue(std::locale(""));
    std::cout << std::locale("").name() << std::endl; // C.UTF-8
    
    wchar_t s {L'\xd0b8'};
    std::wcout << s << std::endl;
    // expected: и
    // actual: 킸
}

  • '\xd0b8'在UTF-8中是и,在UTF-16中是

提到的reference

窄多字节字符串文字(1)和宽字符串文字(2)的编码是实现定义的。例如,gcc使用命令行选项-fexec-charset和-fwide-exec-charset选择它们。

我在Ubuntu 20.04.1 LTS(WSL)中使用g++ -O3 -fwide-exec-charset=UTF-8 source.cc -o out.a && out.a编译并执行了代码,并期望输出и,但是实际输出。 g ++不处理直接用于初始化宽字符s文字字符串中的十六进制。如何让g ++考虑UTF-8中的宽字符?

系统信息:

> lsb_release -a
No LSB modules are available.
distributor ID: Ubuntu
Description:    Ubuntu 20.04.1 LTS
Release:        20.04
Codename:       focal
> g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:hsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 9.3.0-10ubuntu2' --with-bugurl=file:///usr/share/doc/gcc-9/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,gm2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-9 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none,hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 9.3.0 (Ubuntu 9.3.0-10ubuntu2)

解决方法

man gcc

  -fwide-exec-charset=charset
       Set the wide execution character set,used for wide string and character
       constants.  The default is UTF-32 or UTF-16,whichever corresponds to the width
       of "wchar_t".  As with -fexec-charset,charset can be any encoding supported by
       the system's "iconv" library routine; however,you will have problems with
       encodings that do not fit exactly in "wchar_t".

UTF-8是一种多字节编码,不适用于wchar_t。因此,您已经完全掌握了文档中指定的内容:问题。由于Linux上的sizeof(wchar_t)是4,因此您需要指定4字节宽的编码,例如UTF-32。

除了与旧代码交互外,没有任何理由使用wchar_t