I'm writing a C++ extension for PHP and I'm using regex in my code. Here is a snippet
#include <phpcpp.h>
#include <regex>
#include <iterator>
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <stdio.h>
using namespace std;
Element* parse(std::sregex_iterator iterator, std::sregex_iterator iteratorEnd)
{
string segmentContent = "";
// Segment* segment = nullptr;
while (iterator != iteratorEnd)
{
// segment = readSegment(iterator->str());
++iterator;
}
return nullptr;
};
Php::Value parseFromFile(Php::Parameters ¶ms)
{
string filePath = params[0];
ifstream file(filePath);
if (!file.is_open())
{
return nullptr;
}
else
{
// Read the file into a buffer
stringstream buffer;
buffer << file.rdbuf();
// We now have the buffer so we can close the file
file.close();
string regexPattern = string("some pattern here");
std::regex regexMatcher(regexPattern, regex_constants::icase);
string fileContents = buffer.str();
std::sregex_iterator iterator(fileContents.begin(), fileContents.end(), regexMatcher);
std::sregex_iterator iteratorEnd;
root = parseXml(iterator, iteratorEnd);
return Php::Object("SmartXmlParser\\XmlElement", root);
}
};
This won't compile as I haven't included all parts of the code (there is a lot.) It all compiles well here without any errors or warnings. When I try to run a test php file which uses anything from this C++ code it just fails giving the following error.
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php5/20131226/myextension.so' - /usr/lib/php5/20131226/myextension.so: undefined symbol: _ZNSt14regex_iteratorIN9__gnu_cxx17__normal_iteratorIPKcSsEEcSt12regex_traitsIcEEC1Ev in Unknown on line 0
PHP Fatal error: Call to undefined function parseXml() in /home/vagrant/Laravel/extensions/myextension/test.php on line 5
PHP Stack trace:
PHP 1. {main}() /home/vagrant/Laravel/extensions/myextension/test.php:0
Fatal error: Call to undefined function parseXml() in /home/vagrant/Laravel/extensions/myextension/test.php on line 5
Call Stack:
0.0023 220904 1. {main}() /home/vagrant/Laravel/extensions/myextension/test.php:0
As soon as I remove the methods and pieces of code that reference the regex classes it runs fine (I can leave the include and it will still work.)
I compile using these command lines:
g++ -Wall -c -O2 -std=c++11 -fpic -o main.o main.cpp
g++ -shared -o myextension.so main.o -lphpcpp
cp -f myextension.so /usr/lib/php5/20131226
cp -f myextension.ini /etc/php5/cli/conf.d
Since regex is a part of the standard library in C++11 I'd imagine I don't have to link regex manually as it's done automatically at runtime right?
Is there something I'm missing to make it work with PHP? I'm not exposing any regex objects, they're just a means of achieving a goal in my C++ code.