MyCollege1999 2024-04-23 11:07 采纳率: 66.1%
浏览 17
已结题

codeBlocks怎么使用regex.h

想运行网上的一段程序,结果编译报错,头文件不存在

#include <stdio.h>
#include <regex.h>

void format_code(char *code) {
    // 定义正则表达式用于格式化
    const char *pattern = "([{;,]|^)\\s*([a-zA-Z0-9_])";
    regex_t regex;
    regcomp(&regex, pattern, 0);

    regmatch_t pmatch[2];
    int status = regexec(&regex, code, 2, pmatch, 0);

    if (status == 0) {
        // 找到匹配,添加空格
        char *formatted = malloc(pmatch[0].rm_eo + 2);
        memcpy(formatted, code, pmatch[0].rm_so);
        formatted[pmatch[0].rm_so] = ' ';
        memcpy(formatted + pmatch[0].rm_so + 1, code + pmatch[0].rm_eo, pmatch[0].rm_eo - pmatch[0].rm_so);
        strcpy(code, formatted);
        free(formatted);
    }

    regfree(&regex);
}

int main() {
    char code[] = "int main(){int a=10;printf(\"%d\", a);}";
    format_code(code);
    printf("Formatted code: %s\n", code);
    return 0;
}

D:\practice_self\cCodeFormat0422\CCodeFormat.c|2|fatal error: regex.h: No such file or directory|
我选择支持c++11了,因为auto变量可以识别。还是不行。
请问怎么解决呢?

  • 写回答

5条回答 默认 最新

  • 檀越@新空间 2024-04-23 11:07
    关注

    上午好☀️☀️☀️️
    本答案参考ChatGPT-3.5

    问题分析:

    你的程序要使用regex.h头文件中的函数,但编译时却报告头文件不存在的错误。这说明编译器没有找到此头文件,需要添加相应的库。

    解决方案:

    • 方案一:在编译命令中添加指示编译器使用regex库的选项。

      可以在编译程序时添加相关的库,建议使用-lregex选项,表示链接regex库。

      这个选项在Linux系统下编译时可用,用法如下:

      gcc -o test test.c -lregex
      

      如果你在Windows上使用mingw编译工具,可以使用-l选项指定库文件的名称,如下:

      gcc -o test test.c -lregex
      
    • 方案二:添加regex库的路径,告诉编译器头文件在哪里。

      如果你已经安装了regex库,但编译时仍提示找不到头文件,可以使用-I选项来指定头文件所在的路径。

      在Linux系统中使用如下命令:

      gcc -c -o test.o test.c -I/usr/local/include
      

      在Windows上使用如下命令:

      gcc -c -o test.o test.c -I"C:\Program Files\regex\include"
      
    • 方案三:检查是否安装了regex库,如果没有安装则需进行安装。

      在Linux上,安装regex库可以使用如下命令:

      sudo apt-get install libpcre3-dev
      

      在Windows上下载相应的regex库文件,并将其添加到编译器的库路径中即可。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

问题事件

  • 系统已结题 7月26日
  • 已采纳回答 7月18日
  • 创建了问题 4月23日