linker error in boost regex

2020-06-26 04:13发布

I would like to learn something about regex in boost lib and i try compile this simple example code:

// regex_search example
#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main ()
{
  std::string s ("this subject has a submarine as a subsequence");
  boost::smatch m;
  boost::regex e ("\\b(sub)([^ ]*)");   // matches words beginning by "sub"

  std::cout << "Target sequence: " << s << std::endl;
  std::cout << "Regular expression: /\\b(sub)([^ ]*)/" << std::endl;
  std::cout << "The following matches and submatches were found:" << std::endl;

  while (boost::regex_search (s,m,e)) {
    for (auto x:m) std::cout << x << " ";
    std::cout << std::endl;
    s = m.suffix().str();
  }

  return 0;
}

I use: g++ -std=c++0x -I /usr/lib/boost/include -L /usr/lib/boost/lib -lboost_regex test_regex.cpp

but g++ show me:

/tmp/ccjni2je.o: In function `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::assign(char const*, char const*, unsigned int)':
test_regex.cpp:(.text._ZN5boost11basic_regexIcNS_12regex_traitsIcNS_16cpp_regex_traitsIcEEEEE6assignEPKcS7_j[boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::assign(char const*, char const*, unsigned int)]+0x22): undefined reference to `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::do_assign(char const*, char const*, unsigned int)'
/tmp/ccjni2je.o: In function `bool boost::regex_search<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, char, boost::regex_traits<char, boost::cpp_regex_

and much more ...

Can anyone help me ?

1条回答
小情绪 Triste *
2楼-- · 2020-06-26 04:53

Three things:

  1. The Boost.Regex library is likely called libboost_regex-mt.
  2. Unless you know that a Boost lib was compiled with C++11 support, you should remove the
    -std=c++0x option.
  3. You should always place LIBS at the end because GNU ld resolves symbols in the order that object files and LIBS appear in the command line.

Try:

g++ -I /usr/lib/boost/include -L /usr/lib/boost/lib test_regex.cpp -lboost_regex-mt
查看更多
登录 后发表回答