Tuesday, August 14, 2012

Clang does't compile gcc compatible c++ code? -fms-compatibility is your friend

Many people are currently switching from g++ to clang. Unfortunately, not everything that compiles with g++ compiles with clang. Because g++ is less strict then gcc.

E.g.: A software I am working on is dependent on c-client (http://www.washington.edu/imap/). When compiling code that depends on c-client with clang, the following error is prompted:

/opt/local/include/c-client/c-client.h:36:9: error: C++ operator 'and' cannot be used as a macro name
#define and cclientAnd          /* C99 doesn't realize that ISO 646 is dead */

Fortunately, there is compiler option to bypass those problems: -fms-compatibility
Although this parameter was introduced to make clang compile visual c++ headers, it also fixes problems like the one above.

Wednesday, August 10, 2011

X-Macros to Print Enums

Very nice solution to make enums printable with X-macros:

langs.def:
X(XQuery)
X(CPlusPlus)
X(XPath)
X(JavaScript)
X(Java)

main.cpp:
#include <iostream>


enum Langs {
#   define X(a) a,
#   include "langs.def"
#   undef X
};


char const* const langs_str[] = { 
#   define X(a) #a,
#   include "langs.def"
#   undef X
};


std::ostream& operator<<(std::ostream& os, enum Langs c)
{
  return os << langs_str[c];
}


int main()
{
    std::cout << XQuery << " " << XPath << std::endl;
}


Output:

./main 
XQuery XPath