C++11 CMake : Regex fails

标签 c++ regex c++11 cmake g++4.9

我遇到了 gcc/g++ <= 4.8.X 不支持 RegEx 的问题(我的第一 react 是:什么?!)。

安装 (Ubuntu 14.04 LTS) gcc-4.9 和 g++-4.9(应该正确支持 RegEx)后,我仍然遇到同样的错误:

terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
[1]    13608 abort (core dumped)

我的 CMakeLists.txt 看起来像这样(使用 Jetbrains CLion 作为 IDE):

set(CMAKE_CXX_COMPILER g++-4.9)

cmake_minimum_required(VERSION 3.1)

project(project1)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES main.cpp)

add_executable(project1 ${SOURCE_FILES})

我的代码如下所示:

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

using namespace std;

(...)

char encryptChar(char cinput)
{
    std::string s = std::string(1, cinput);
    // simplified regex (also crashes)
    std::regex e = std::regex("[a-z]");

    if(std::regex_match(s, e))
    {
        // do some stuff, if string matches conditions
    }

    return cinput;
}

编译器/链接器不会提示任何事情。程序在没有正则表达式的情况下运行良好。

> g++-4.9 --version
>>> g++-4.9 (Ubuntu 4.9.2-0ubuntu1~14.04) 4.9.2
>>> Copyright (C) 2014 Free Software Foundation, Inc.

编辑:使用g++-4.9 -std=c++11 main.cpp 手动编译代码后,正则表达式起作用。为什么IDE/CMake版本会失败?

最佳答案

终于找到问题了:

我的 CMake 版本是 2.8-ish,所以 CMake 本身失败了,Jetbrains CLion 使用自定义 CMake(随 IDE 一起提供),它是 3.1-ish 但也因 RegEx 而失败。

我下载了CMake 3.2.2 (最新版本)并安装它(installation notes)。现在用 CMake 编译正确使用 g++-4.9 并且 RegEx 运行良好。在 CLion 中,我不得不更改设置以忽略自定义 CMake 并使用我的系统 CMake 3.2.2,现在使用 IDE 编译也正确使用 g++-4.9,RegEx 运行良好。

关于C++11 CMake : Regex fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29751137/

相关文章:

c++ - 递归地扩展类和函数的可变参数模板

c++ - 用右值初始化左值引用

c++ - 将 boost::geometry 多边形转换为 STL 对象

Python删除字符直到字母或数字

regex - 泛数字正则表达式?

regex - 如何根据时间间隔获取这些错误/不匹配字符串

c++ - 如何将 int unique_ptr 转换为 void unique_ptr?

c++ - VS2008| : Memory use discrepancy between Task Manager and CRT Heap Debugger functions

c++ - 增量运算符不适用于 sizeof

c++11 - 如何定义 constexpr 变量