当前位置: 首页 > news >正文

linux c++头文件生成源文件 使用python脚本 配置vim快捷键

在编写c++头文件后,还需要再.cpp文件里面复制一份非常的麻烦

找过了不少方法都很难实现

提供了一个python脚本帮助你实现这个过程

#!/usr/bin/env python3                                                                                                                                                              
import re
import sysdef process_class(content):"""提取并处理内容中的下一个类,返回函数定义和剩余内容。"""class_match = re.search(r'class\s+(\w+)(?:\s*:\s*\w+)?', content)if not class_match:return None, contentclass_name = class_match.group(1)class_start = re.search(rf'class\s+{class_name}(?:\s*:\s*\w+)?\s*{{', content)start_pos = class_start.end() - 1brace_count = 1i = start_pos + 1while i < len(content) and brace_count > 0:if content[i] == '{':brace_count += 1elif content[i] == '}':brace_count -= 1i += 1class_content = content[start_pos:i]remaining_content = content[i:]# 移除访问修饰符class_content = re.sub(r'^\s*(public|private|protected):\s*', '', class_content, flags=re.MULTILINE)# 查找函数声明func_pattern = r'(friend\s+)?([\w:&<>]+\s*[\*&]?\s*)?(operator[\w<>=!+\-*]+)?\s*(\w+)?\s*\(([^)]*)\)\s*(const)?\s*;'functions = re.findall(func_pattern, class_content, re.MULTILINE)definitions = []for func in functions:friend, return_type, op_name, func_name, params, const = func# 清理参数:移除默认值cleaned_params = []for p in params.split(','):p = p.strip()if p:p = re.sub(r'\s*=\s*[^,)]+', '', p)cleaned_params.append(p)params = ', '.join(cleaned_params)# 清理非友元函数的返回类型if not friend and return_type:while return_type.startswith(('static ', 'virtual ', 'explicit ')):return_type = return_type.split(' ', 1)[1].strip()return_type = return_type.strip() if return_type else ''const = ' const' if const else ''if op_name:func_name = f'operator{op_name[len("operator"):]}'elif not func_name:continueif friend:func_def = f"{return_type} {func_name}({params}){const} {{\n     \n}}\n"else:func_def = f"{return_type} {class_name}::{func_name}({params}){const} {{\n     \n}}\n"definitions.append(func_def)return definitions, remaining_contentdef process_global_functions(content):"""提取并为没有定义体的全局函数生成定义。"""# 正则表达式匹配没有函数体的全局函数声明global_func_pattern = r'^\s*(?!class|struct)(\w+\s+)+(\w+)(\s*\([^;]*\))\s*;'matches = re.finditer(global_func_pattern, content, re.MULTILINE)definitions = []for match in matches:full_match = match.group(0)# 提取返回类型、函数名和参数return_type = match.group(1).strip()func_name = match.group(2).strip()params = match.group(3).strip()# 清理参数:移除默认值cleaned_params = []for p in params[1:-1].split(','):p = p.strip()if p:p = re.sub(r'\s*=\s*[^,)]+', '', p)cleaned_params.append(p)params = ', '.join(cleaned_params)func_def = f"{return_type} {func_name}({params}) {{\n    \n}}\n"definitions.append(func_def)return definitionsdef process_header(input_file, output_file):"""处理头文件并生成对应的 .cpp 文件。"""with open(input_file, 'r', encoding='utf-8') as f:content = f.read()function_definitions = []# 处理所有类while True:defs, content = process_class(content)if defs is None:breakfunction_definitions.extend(defs)# 处理全局函数global_defs = process_global_functions(content)function_definitions.extend(global_defs)# 写入输出文件output = [f'#include "{input_file}"\n\n'] + function_definitionswith open(output_file, 'w', encoding='utf-8') as f:f.writelines(output)print(f"成功生成 {output_file}!") # 这一行建议注释掉if __name__ == '__main__':if len(sys.argv) < 2:print("用法: python3 script.py input.h [output.cpp]")sys.exit(1)input_path = sys.argv[1]output_path = sys.argv[2] if len(sys.argv) >= 3 else input_path.replace('.h', '.cpp')process_header(input_path, output_path)

这个脚本接收两个参数,第一个是你的头文件,第二个是输出的地址,可以不提供第二个地址,则默认以cpp结尾存储再当前目录

全局脚本调用

~/.local/bin 是用户专属的可执行文件目录,推荐用于全局调用。
查看是否存在,不存在则手动创建一下

mkdir -p ~/.local/bin

然后把python脚本放到这个目录下
在这里插入图片描述
注意看一下是否有执行权限
在这里插入图片描述
没有的话添加一下

chmod +x ~/.local/bin/generate_cpp.py

然后需要配置环境变量
查看当前环境

echo $PATH

查看这个目录是否在环境下
不在的话我们添加一下

vim ~/.bashrc

把下面这个添加到最后一行

export PATH="$HOME/.local/bin:$PATH"

再重启一下

source ~/.bashrc

你就可以看到了
在这里插入图片描述
然后我们就能全局调用这个脚本

测试示例

在这里插入图片描述

#pragma once
#include <iostream>class Stonewt
{
public:enum Mode { STONE, POUND, INT };private:enum { Lbs_per_stn = 14 };int stone;double pds_left;double pounds;Mode mode;public:Stonewt(double lbs, Mode form = STONE);Stonewt(int stn, double lbs, Mode form = STONE);Stonewt(){stone = pounds = pds_left = 0;mode = STONE;}void stoneMode() { mode = STONE; }void poundMode() { mode = POUND; }void intMode() { mode = INT; }~Stonewt(){};bool operator<(const Stonewt &s);bool operator>(const Stonewt &s);bool operator<=(const Stonewt &s);bool operator>=(const Stonewt &s);bool operator==(const Stonewt &s);bool operator!=(const Stonewt &s);Stonewt operator+(const Stonewt &s);Stonewt operator-(const Stonewt &s);Stonewt operator-();friend Stonewt operator*(const Stonewt &s1, const Stonewt &s2);friend std::ostream &operator<<(std::ostream &os, const Stonewt &);friend std::istream &operator>>(std::istream &os, Stonewt &);
};
class test:Stonewt{
public:void fun1();virtual void fun2() const;static void fun3();
};
void show(const Stonewt & st);
void func();

测试示例来自c++Primerplus编程练习第11章第6题

这是生成的stonewt.cpp文件

#include "stonewt.h"Stonewt::Stonewt(double lbs, Mode form) {}Stonewt::Stonewt(int stn, double lbs, Mode form) {}bool Stonewt::operator<(const Stonewt &s) {}bool Stonewt::operator>(const Stonewt &s) {}bool Stonewt::operator<=(const Stonewt &s) {}bool Stonewt::operator>=(const Stonewt &s) {}bool Stonewt::operator==(const Stonewt &s) {}bool Stonewt::operator!=(const Stonewt &s) {}
✹ Stonewt Stonewt::operator+(const Stonewt &s) {}
✹ Stonewt Stonewt::operator-(const Stonewt &s) {}Stonewt Stonewt::operator-() {}
✹ Stonewt operator*(const Stonewt &s1, const Stonewt &s2) {}
✹ std::ostream & operator<<(std::ostream &os, const Stonewt &) {}
✹ std::istream & operator>>(std::istream &os, Stonewt &) {}void test::fun1() {}void test::fun2() const {}void test::fun3() {}void show(const Stonewt & st) {}void func() {}

这些是vim的提示,实际上没有

vim中调用

注意要完成前面的全局配置
推荐安装vimplus,可以参考这里

:!generate_cpp.py % %.cpp 

可以直接用这个调用,可以省略%.cpp

配置快捷键

添加我们自己的配置

 vim ~/.vimrc.custom.config 

在其中添加这样的内容,你就可以使用,cpp来生成源文件了

function! GenerateCpp()writelet output = system('generate_cpp.py ' . expand('%') . ' ' . expand('%:r') . '.cpp')if v:shell_errorcopencaddexpr outputecho "Error generating " . expand('%:r') . ".cpp"elseecho "Generated " . expand('%:r') . ".cpp successfully!"endif
endfunctionautocmd FileType cpp,h nnoremap <silent> <leader>cpp :call GenerateCpp()<CR>  

相关文章:

  • Unity3D仿星露谷物语开发44之收集农作物
  • OAuth2.0
  • 6to4、6over4的类比解释
  • 使用tensorRT10部署低光照补偿模型
  • MySQL相关
  • [强化学习的数学原理—赵世钰老师]学习笔记02-贝尔曼方程
  • 支持selenium的chrome driver更新到136.0.7103.94
  • 【2025年软考中级】第一章1.6 安全性、可靠性、性能评价
  • Python爬虫实战:获取1688商品信息
  • 无需配置光猫,使用网管交换机配合路由器的IPTV功能实现单线复用
  • Uniapp开发鸿蒙应用时如何运行和调试项目
  • Kotlin与机器学习实战:Android端集成TensorFlow Lite全指南
  • 从神经架构到万物自动化的 AI 革命:解码深度学习驱动的智能自动化新范式
  • 人工智能100问☞第25问:什么是循环神经网络(RNN)?
  • 基于OpenCV的SIFT特征和FLANN匹配器的指纹认证
  • 互联网大厂Java面试:从Spring到微服务的全面探讨
  • Spring Initializr快速创建项目案例
  • QT使用QXlsx读取excel表格中的图片
  • OGGMA 21c 微服务 (MySQL) 安装避坑指南
  • 25、DeepSeek-R1论文笔记
  • 湖南4个县市区被确定为野生蘑菇中毒高风险区:中毒尚无特效解毒药
  • 俄乌直接谈判结束
  • 阿联酋与美国达成超过2000亿美元协议
  • 中国人民银行等四部门联合召开科技金融工作交流推进会
  • 刘强东坐镇京东一线:管理层培训1800人次,最注重用户体验
  • 马上评|让查重回归促进学术规范的本意