Search code examples
c++c-preprocessor

Embedding JSON as a string in C++ code using preprocessor


I saw a mix of C++ and JSON code in the Chromium project.

For example in this file: config/software_rendering_list_json.cc

#define LONG_STRING_CONST(...) #__VA_ARGS__

const char kSoftwareRenderingListJson[] = LONG_STRING_CONST(
{
  "name": "software rendering list",
  // Please update the version number whenever you change this file.
  "version": "6.15",
  "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"
      ]
    }
    // . . .
  ]
}
);

Is the magic with this macro?

#define LONG_STRING_CONST(...) #__VA_ARGS__

How does it "stringify" arbitrary JSON content?


Solution

  • You guessed right!

    # inside a macro body turns the subsequent token into a C string literal containing that token's text. In this case, the next token is the special __VA_ARGS__ macro keyword that is substituted with all the arguments to the (variadic) macro, which corresponds to the JSON in the source code.