C++11 regex using g++

Boost regex has been accepted into C++11. So, I decided to give it a try using g++.

#include<iostream>
#include<string>
#include<regex>

using namespace std;

int main() {
        string str("2 a\n3 b\n4 c\n5 d\n6 c");
        regex r("[0-9]");

        regex_iterator<string::iterator> start(str.begin(), str.end(), r);
        regex_iterator<string::iterator> end;

        while(start != end) {
                cout << start->str() << endl;
                ++start;
        }
}

I was surprised to get a big fat link-time error:

/tmp/cc80j8Z8.o: In function `main':
regex1.cpp:(.text+0x133): undefined reference to `std::regex_iterator<__gnu_cxx::__normal_iterator<char*, std::string>, char, std::regex_traits >::regex_iterator(__gnu_cxx::__normal_iterator<char*, std::string>, __gnu_cxx::__normal_iterator<char*, std::string>, std::basic_regex<char, std::regex_traits > const&, std::bitset)’
regex1.cpp:(.text+0x13f): undefined reference to `std::regex_iterator<__gnu_cxx::__normal_iterator<char*, std::string>, char, std::regex_traits >::regex_iterator()’
regex1.cpp:(.text+0x150): undefined reference to `std::regex_iterator<__gnu_cxx::__normal_iterator<char*, std::string>, char, std::regex_traits >::operator->()’
regex1.cpp:(.text+0x1a9): undefined reference to `std::regex_iterator<__gnu_cxx::__normal_iterator<char*, std::string>, char, std::regex_traits >::operator++()’
regex1.cpp:(.text+0x1bf): undefined reference to `std::regex_iterator<__gnu_cxx::__normal_iterator<char*, std::string>, char, std::regex_traits >::operator!=(std::regex_iterator<__gnu_cxx::__normal_iterator<char*, std::string>, char, std::regex_traits > const&)’
collect2: error: ld returned 1 exit status

Seems like gcc 4.8.2, delivered by my distribution doesn’t support regex yet. So, we are forced to use Boost regex for now.¬†Or use g++ 4.9.0 instead, which has regex implemented. To install the latest g++ release, execute the following command in the terminal:

sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install g++-4.9

To compile the code with g++4.9:

g++-4.9 --std=c++11 regex1.cpp -o regex1

tejainece

Ravi Teja is a technology entrepreneur with interest in Embedded Systems, Software engineering, Operating Systems, Web development, Cloud computing, Machine learning, etc.

More Posts - Website

Follow Me:
LinkedInGoogle Plus