LoginSignup
4
6

More than 5 years have passed since last update.

`#pragma execution_character_set("utf-8")` は翻訳単位ごとに反映される

Posted at

 MSVC の #pragma execution_character_set について、公式のドキュメントが見つけられなかったのと、この pragma をソースファイルに書いた時、翻訳単位ごとに効くのかリンクした実行ファイル全体に効くのか不安だったので調べた。結論はタイトルの通り。

調査方法

  • Visual Studio Professional 2013 Version 12.0.30723.00 Update 3 で検証した
  • "Win32 コンソールアプリケーション" のプロジェクトを作り、以下のソース、ヘッダファイルを用意した。全部 CP932 で保存した。
  • #pragma execution_character_set("utf-8") を書いたソースと書いてないソースでそれぞれ文字列定数を定義し、main でこれをダンプする、というもの。
ConsoleApplication.cpp
#include "stdafx.h"
#include "./default.h"
#include "./utf8.h"
#include <iostream>
#include <algorithm>

static void dump_string_bytes(std::string const& s)
{
    std::cout << '"' << s << '"' << std::endl;
    std::for_each(s.cbegin(), s.cend(), [](char c) {
        std::cout << "0x" << std::hex << (c & 0xFF) << std::dec << " ";
    });
    std::cout << std::endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    std::cout << "[UTF8]" << std::endl;
    dump_string_bytes(kMessageUTF8);

    std::cout << "[Default]" << std::endl;
    dump_string_bytes(kMessageDefault);

    return 0;
}
default.cpp
#include "stdafx.h"
#include "./default.h"

std::string const kMessageDefault = "あいうえお";
default.h
#pragma once

#include <string>

extern std::string const kMessageDefault;
utf8.cpp
#include "stdafx.h"
#include "./utf8.h"

#pragma execution_character_set("utf-8")

std::string const kMessageUTF8 = "あいうえお";
utf8.h
#pragma once

#include <string>

extern std::string const kMessageUTF8;
  • 出力結果
[UTF8]
"縺ゅ>縺・∴縺・
0xe3 0x81 0x82 0xe3 0x81 0x84 0xe3 0x81 0x86 0xe3 0x81 0x88 0xe3 0x81 0x8a 
[Default]
"あいうえお"
0x82 0xa0 0x82 0xa2 0x82 0xa4 0x82 0xa6 0x82 0xa8 
  • 結論: ソースファイルに書いた #pragma execution_character_set("utf-8") は翻訳単位ごとに効くっぽい。
4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6