修改了CUBEMX库函数怎么办,避免修改代码被更新

本文介绍了如何在Cubemx生成的代码中编辑底层库函数和宏定义,提供了两种方法:一是利用预处理和后处理区,二是使用Python脚本实现多行替换。作者还分享了一个Python示例用于替换USB设备描述文件中的特定字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们都知道,cubemx生成的代码只允许用户在注释段中编写自己的代码,但是往往有时候需要对某些涉及底层的库函数或者一些宏定义进行编辑,为了避免自己编辑的代码在再次使用cubemx时被替换掉,起初我尝试了自己添加注释

  /* USER CODE BEGIN XX */

  /* USER CODE END XX*/

尝试失败,同时找到官方说不支持用户自己添加这样的注释块。

我在这里提供两个方法

1、针对代码前后都有注释块,而中间要修改的部分没有时


void MX_XXX_Init(void)
{
  /* USER CODE BEGIN Init_PreTreatment */
    #define CPRE
	#ifdef CPRE
	//用户代码
    //用户代码
	#else
  /* USER CODE END Init_PreTreatment */
 	//系统代码
    //系统代码
  /* USER CODE BEGIN Init_PostTreatment */
	#endif
  /* USER CODE END Init_PostTreatment */
}

2、更为普遍的替换情况,这里给出一个简单得到python程序,亲测可用

def auto_replace(f_str,r_str,filepath):
    assert(len(f_str)==len(r_str))
    with open(filepath,'r')as f:
        lines=f.readlines()
        need_replace_line_num=0#len(find_strs)
        for l in range(0,len(lines)):
            if lines[l]==f_str[need_replace_line_num]:
                print(lines[l])
                lines[l]=r_str[need_replace_line_num]
                need_replace_line_num+=1
                if need_replace_line_num==len(f_str):
                    break
        if need_replace_line_num==0:
            print(filepath," warning :cannot find any string to replace")
        else:
            print(filepath," replaced:",need_replace_line_num)
    with open(filepath,'w+')as f:
        f.writelines(lines)


if __name__=="__main__":
    find_strs=["  0x00,                       /*bDeviceClass*/\n",
                "  0x00,                       /*bDeviceSubClass*/\n",
                "  0x00,                       /*bDeviceProtocol*/\n"]
    replace_strs=["  0x02,                       /*bDeviceClass*/\n",
                    "  0x02,                       /*bDeviceSubClass*/\n",
                    "  0x01,                       /*bDeviceProtocol*/\n"]
    file_path='USB_DEVICE\\App\\usbd_desc.c'
    auto_replace(find_strs,replace_strs,file_path)

    #对于多个文件的替换可以多次追加

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值