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

`wide-exec-charset` dose not change the charset of `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: 킸
}

reference提到:

The encoding of narrow multibyte string literals (1) and wide string literals (2) is implementation-defined. For example, gcc selects them with the commandline options -fexec-charset and -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 是一种 multi-byte 编码,不完全适合 wchar_t。所以你得到的正是文档中指定的内容:问题。由于 Linux 上的 sizeof(wchar_t) 为 4,因此需要指定 4-bytes-wide 编码,例如 UTF-32。

没有真正的理由将 wchar_t 用于任何除了与旧代码交互之外的任何事情。