c++cpprest-sdk

How does cpprestsdk use macros to define constants?


For example in include/cpprest/http_msg.h the header_names is defined as:

class header_names
{
public:
#define _HEADER_NAMES
#define DAT(a, b) _ASYNCRTIMP const static utility::string_t a;
#include "cpprest/details/http_constants.dat"
#undef _HEADER_NAMES
#undef DAT
};

and in cpprest/details/http_constants.dat there would be a section like this:

#ifdef _HEADER_NAMES
DAT(accept,                 "Accept")
DAT(accept_charset,         "Accept-Charset")
...
#endif

from the DAT(a, b) definition, the variable b is not used.

However when we do a simple assignment:

auto a = header_names::accept;

the variable a contains the string "Accept".

I'm not sure how could this happen.

I use godbolt.org with option -E to get pre-processor of the following code

class header_names
{
public:
#define DAT(a, b) _ASYNCRTIMP const static utility::string_t a;
DAT(accept,                 "Accept")
DAT(accept_charset,         "Accept-Charset")
#undef DAT
};

and the generated result is

class header_names
{

_ASYNCRTIMP const static utility::string_t accept;
_ASYNCRTIMP const static utility::string_t accept_charset;

};

Solution

  • The header file contains the class declaration of the static variables. The corresponding definitions, including the initializations, are in release/src/http/common/http_msg.cpp.

    #define _HEADER_NAMES
    #define DAT(a, b) const utility::string_t header_names::a = _XPLATSTR(b);
    #include "cpprest/details/http_constants.dat"
    #undef _HEADER_NAMES
    #undef DAT