How do I get PCRE to work with C++?

Mike  picture Mike · Oct 13, 2010 · Viewed 12.2k times · Source

This is a newbie question but I hope I can express my question as clearly as possible.

I'm trying to do pattern matching in C++.

I've downloaded the Win32 version of PCRE from here and I've placed the downloaded pcre3.dll and pcreposix3.dll files into the folder of Dev-CPP's lib folder (I'm using Bloodshed Dev-C++ 4.9.9 IDE).

I've also downloaded a pcrecpp.h header file and have it in the same directory I'm writing the following code (not writing actually. I'm coping example code from a PDF tutorial named PCRE- Perl Compatible Regular Express).

But I can't get it to work. The code is as follows:

    #include <iostream>
    #include <string>
    #include <pcrecpp.h>

    using namespace std;

    int main()
    {
       int i;
       string s;
       pcrecpp::RE re("(\\w+):(\\d+)");
       if (re.error().length() > 0) {
          cout << "PCRE compilation failed with error: " << re.error() << "\n";
       }
       if (re.PartialMatch("root:1234", &s, &i))
       cout << s << " : " << i << "\n";
    }

When I compile the code, Dev-C++ gives me a lot of errors including: "`pcrecpp' has not been declared" and "RE" undeclared.

How should I deal with the downloaded files and fix my problem? Or is there something obvious that I'm missing?

Answer

Bart van Ingen Schenau picture Bart van Ingen Schenau · Oct 13, 2010

If you specify the file for #include with angle brackets (<>), then the compiler will only look for that header in the locations for external libraries, in so far as the compiler is aware of them.
If you instead use quotation marks (""), then the compiler will also look in the locations for the current project, which typically includes the current directory.

The quick fix for your current problem is to use

#include "pcrecpp.h"

The alternative is to tell the compiler where it can find the headers of the PCRE library.
You will have to tell the compiler where it can find the headers of the PCRE library. How to do this differs from build system to build system, but if you are using an IDE, then there should be an option somewhere to specify the 'Include directories'. This is where you add the directory of the PCRE headers (with full path).


As a side-note: When the compiler gives you a large number of errors and warnings, always start with fixing the first one. I would guess that in this case it was something like "unable to find header: pcrecpp.h".
It is often the case that, if the compiler tries to continue after encountering a problem, more problems are found that are follow-on problems of the first one. When the first problem is fixed, these also magically disappear.