sorush-r sorush-r - 1 year ago 41
C++ Question

Replace characters in preprocessor definition

I have a definition which includes a path (with no escape sequence) like this one:

// Incorrect
#define PATH "c:\blah\blah\file.cfg"

I would rather like it as this:

// Corrected
#define PATH "c:\\blah\\blah\\file.cfg"

Though unfortunately I can not modify the macro definition (actually the script that generates the source that includes the macro...), except for adding prefixes. Now I need to open the file given in this path. I tried c++11 raw string literals like this:

// Modified definition
#define PATH R"c:\blah\blah\file.cfg"
std::ifstream(PATH); // error: unrecognised escape sequence

Now the question is how to replace all
using a macro?

Notes (if does matter):

Compiler: MSVC 14.0

OS: Windows 7

Answer Source

You could make use of the preprocessor's stringify-operator #, which does not only encapsulate the parameter in double quotes but also escapes "ordinary" backslashes in the string. Then - at runtime - cut off the extra double quotes introduced by the stringify.

So the idea is the following:

  1. somehow stringify PATH such that "c:\blah\blah\file.cfg" becomes "\"c:\\blah\\blah\\file.cfg\"". Note that the string itself contains double quotes as the first and the last character then.

  2. at runtime, use substr to cut the value between the (unwanted) double quotes

A bit tricky is to stringify a value that is itself provided as a macro. To do that, you can use a macro with variadic arguments (as these get expanded). So the complete code would look as follows:

#define PATH "c:\blah\blah\file.cfg"

#define NORMALIZEPATH(P) string(STRINGIFY(P)).substr(1,strlen(STRINGIFY(P))-2)

int main() {

    string filename =  NORMALIZEPATH(PATH);
    cout << "filename: " << filename << endl;

    return 0;


filename: c:\blah\blah\file.cfg
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download