Monday 10 April 2017

Fixing "Error C2059: syntax error : '('" in xlocale

Introduction

When you use std::string in a relatively large project, you may see the following error message that is hard to understand. 


The source code block complained about this is like this: 


The compiler didn't like the line of 'global(const locale&);' which looked just normal. This compiles with no error if you configure a new project, which makes it look more strange. 

Troubleshooting

The problem is simply caused by the 'global' keyword. Yeah, the project actually uses this keyword for another purpose. For my case, it is defined like this to indicate the function is globally referenced: 


Now it's very easy to understand - the 'global' in xlocale has been replaced by 'nothing' so that the line must have been transformed like this:

static _MRTIMP2_PURE locale __CLRCALL_PURE_OR_CDECL
       (const locale&);

As you can see here, the function definition on xlocale is certainly corrupted now by the 'global' keyword defined already for another purpose.

Fix

You may like to remove the definition of 'global' that looks unnecessary, but unfortunately it was used in so many places in my case that I couldn't do this. But now you understand the reason (there exists '#define global' somewhere before including <string>), we have three workarounds at least. 

  1. Use #undef before #include <string>, or 
  2. Remove #include <string> from your new header file and reference it on the cpp file, or 
  3. Do '#include <string>' (or including the header file that does '#include <string>' before having #define global (or including the header file that does '#define global'). eg.
    • (TestVictim.cpp) 
      #include <Windows.h>
      #include ....                          // (other system includes)
      #include "ImIncludingString.h"         // has #include <string>
      #include "ImDefiningGlobal.h"          // has #define global

#3 is probably the best way as it has no affect on other source files. 


Evernote helps you remember everything and get organized effortlessly. Download Evernote.

No comments: