我们都知道,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)
#对于多个文件的替换可以多次追加