C++11 CMake:正则表达式失败

C++11 CMake: Regex fails

本文关键字:失败 正则表达式 CMake C++11      更新时间:2023-10-16

我遇到了gcc/g ++ <= 4.8.X不支持正则表达式的问题(我的第一反应是:什么?!

安装(Ubuntu 14.04 LTS)gcc-4.9 和 g++-4.9(应该正确支持正则表达式)后,我仍然得到相同的错误:

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左右,所以CMake本身失败了,Jetbrains CLion使用自定义CMake(随IDE一起提供),大约是3.1左右,但在RegEx中也失败了。

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