Search code examples
visual-c++utf-8cmakecharacter-encoding

Possible to force CMake/MSVC to use UTF-8 encoding for source files without a BOM? C4819


All our source code is valid UTF-8, however some users on Windows cannot build them because their system is configured for a different encoding.

Without adding a BOM to source files, is it possible to tell MSVC to treat all source as UTF-8, irrespective of the users system encoding?

See MSDN's link regarding this topic (requires adding BOM header).


Solution

  • You can try:

    add_compile_options("$<$<C_COMPILER_ID:MSVC>:/utf-8>")
    add_compile_options("$<$<CXX_COMPILER_ID:MSVC>:/utf-8>")
    

    By default, Visual Studio detects a byte-order mark to determine if the source file is in an encoded Unicode format, for example, UTF-16 or UTF-8. If no byte-order mark is found, it assumes the source file is encoded using the current user code page, unless you have specified a code page by using /utf-8 or the /source-charset option.

    References