使用预处理器将JSON作为字符串嵌入C ++代码中

rus*_*tyx 6 c++ c-preprocessor

我在Chromium项目中看到了C ++和JSON代码的混合体。

例如在此文件中: config / software_rendering_list_json.cc

这个宏是魔术吗?

#define LONG_STRING_CONST(...) #__VA_ARGS__
Run Code Online (Sandbox Code Playgroud)

如何“字符串化”任意JSON内容?

Jod*_*ins 6

卡梅伦的答案是绝对正确的。

但是,从C ++ 11开始,就有了编译器支持的用于创建原始字符串文字的方法。

char const *string = R"someToken({
  "name": "software rendering list",
  "version": "10.9",
  "entries": [
    {
      "id": 1,
      "description": "ATI Radeon X1900 is not compatible with WebGL on the Mac",
      "webkit_bugs": [47028],
      "os": {
        "type": "macosx"
      },
      "vendor_id": "0x1002",
      "device_id": ["0x7249"],
      "features": [
        "webgl",
        "flash_3d",
        "flash_stage3d"
      ]
    },
    {
      "id": 3,
      "description": "GL driver is software rendered. GPU acceleration is disabled",
      "cr_bugs": [59302, 315217],
      "os": {
        "type": "linux"
      },
      "gl_renderer": "(?i).*software.*",
      "features": [
        "all"
      ]
    }
  ]
})someToken";
Run Code Online (Sandbox Code Playgroud)

但是请注意,存在一些细微的差异。

最明显的是,该宏将摆脱C / C ++注释,并且该宏会将所有空白合并为一个空格。

有关字符串文字的更多详细信息可以在很多地方找到。我喜欢这个


Cam*_*ron 2

你猜对了!

#在宏体内将后续标记转换为包含该标记文本的 C 字符串文字。在这种情况下,下一个标记是特殊的__VA_ARGS__宏关键字,它被替换为(可变参数)宏的所有参数,它对应于源代码中的 JSON。