jotadepicas
jotadepicas

Reputation: 2493

How to work with regular expressions in c++ with gcc 4.8 and without C++11 flag?

I recently found out that regex support in gcc 4.8 is incomplete, and it was truly implemented in gcc 4.9 (see Is gcc 4.8 or earlier buggy about regular expressions?).

So, wanting to work with regex in my c++ program, I updated my gcc to 4.9 following this instructions (https://askubuntu.com/questions/466651/how-do-i-use-the-latest-gcc-4-9-on-ubuntu-14-04).

Now when I try to compile my program it says that in order to #include <regex> I have to specify the compiler flag -std=c++11, which I did, and now I'm faced with new compilation problems that I didn' had before (‘constexpr’ needed for in-class initialization of static data member).

Given that, I think for now it is best to stick to gcc 4.8 and not specify the gnu++11 flag in compilation. Back to square 1.

So, can I work with regular expressions in c++ if I do not want to switch to gcc 4.9 nor flag the compiler with c++11? Is there another way?

Thanks!

PS: actually it's the c++11 flag that causes the compilation issues, not the version of gcc, right?

Upvotes: 1

Views: 1334

Answers (2)

Jonathan Wakely
Jonathan Wakely

Reputation: 171263

The error most likely means you were relying on a non-standard GCC extension to initialize a non-integer type like this:

struct X {
  static const double d = 3.14;
};

That was not valid in C++98, but was supported by GCC.

The C++11 standard added support for initializing non-integer types like that, but you need to use constexpr e.g.

struct X {
  static constexpr double d = 3.14;
};

When you compile with -std=c++11 or -std=gnu++11 the old GCC-specific extension is no longer supported. and you have to use the standard C++11 way, using constexpr.

So you could easily resolve the error by changing it to constexpr, or to make it compatible with GCC's C++98 extension and also C++11:

struct X {
#if __cplusplus > 199711L
  static constexpr double d = 3.14;
#else
  // this is non-standard but allowed by GCC in C++98 mode
  static const double d = 3.14;
#endif
};

That will allow you to compile with -std=c++11, and so you can use GCC 4.9's working std::regex.

Upvotes: 1

Chris Dodd
Chris Dodd

Reputation: 126203

You can install the PCRE library and use that instead of the C++11 standard regular expressions. PCRE is really designed as a C library/interface, rather than C++, but writing a couple of trivial wrapper classes or just using it as a C library is quite easy.

Upvotes: 2

Related Questions