zoukankan      html  css  js  c++  java
  • Linux Tips: 批量修改C语言工程的函数命名风格(Shell+Python方法)

    • 通过ctags解析工程目录中所有函数
    # 遍历所有C文件并将解析出的函数名放在funcs文件中
    find ./ -name "*.[ch]" -exec ctags -x --c-types=f {} ; | awk '{print $1}' >> funcs
    
    • 通过python脚本生成函数转换表并转换
    #!/usr/bin/python3
    # -*- coding=utf-8 -*-
    
    import os
    import sys
    import subprocess
    
    def style_convert(func):
        ''' 函数命名风格转换
        小写加下划线转换为驼峰方式'''
    
        new_func = func[0]
        for i in range(1, len(func)):
            if func[i] == '_':
                func[i + 1] = func[i + 1].upper()
            else:
                new_func += func[i]
    
        return new_func
    
    def codestyle_covert(prj_dir):
        ''' 转换一个工程目录下所有C文件的函数命名风格 '''
    
        # 读取待转换函数
        funcs_file = '{}/funcs'.format(prj_dir)
        with open(funcs_file, 'r') as f:
            funcs = f.readlines()
    
        # 去掉换行符
        funcs = [func.strip() for func in funcs]
    
        # 生成函数转换表
        funcmap = [(func, style_convert(list(func))) for func in funcs]
    
        # 获取工程目录下所有.c.h文件
        cmd = ['find', prj_dir, '-name', '*.[ch]']
        files = subprocess.check_output(cmd).decode('utf-8').split()
    
        # 对所有文件执行函数替换操作
        for f in files:
            print("Coverting {}...".format(f), end='', flush=True)
            for fm in funcmap:
                cmd = ['sed', '-i', r's/<{}>/{}/g'.format(fm[0], fm[1]), f]
                subprocess.call(cmd)
                print('.', end='', flush=True)
            print('.done')
    
    
    def main():
        if len(sys.argv) < 2:
            print("[Error]: No input project directory.")
            exit(0)
    
        prj_dir = sys.argv[1];
        if not os.path.isdir(prj_dir):
            print("Invalid project directory:", prj_dir)
            exit(0)
    
        codestyle_covert(prj_dir)
    
    if __name__ == '__main__':
        main()
    
    • 实例展示
    1. 转换前工程目录状况和函数定义

    2. 解析所有函数

    3. 执行转换,再次查看函数定义

  • 相关阅读:
    nvidia tx1使用记录--基本环境搭建
    STL hashtable阅读记录
    Linux strace命令
    转一篇:Reactor模式
    C++ 模板特化以及Typelist的相关理解
    C++ 内联函数inline
    迭代器失效的几种情况总结
    C++ Class与Struct的区别
    C++中string.find()函数,string.find_first_of函数与string::npos
    C/C++ 中长度为0的数组
  • 原文地址:https://www.cnblogs.com/tp1226/p/15465385.html
Copyright © 2011-2022 走看看