6

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

For example in this file: config/software_rendering_list_json.cc

Is the magic with this macro?

#define LONG_STRING_CONST(...) #__VA_ARGS__

How does it "stringify" arbitrary JSON content?

rustyx
  • 80,671
  • 25
  • 200
  • 267

2 Answers2

9

Cameron's answer is absolutely correct.

However, since C++11, there is a compiler supported method for creating raw string literals.

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";

Note, however, that there are several subtle differences.

Most obviously, the macro will get rid of C/C++ comments and the macro will coalesce all whitespace into a single space.

Further details about string literals can be found in lots of places. I like this one.

Jody Hagins
  • 27,943
  • 6
  • 58
  • 87
2

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.

Cameron
  • 96,106
  • 25
  • 196
  • 225