写了一个简陋的程序,用来自动修改 mdk 生成的 APP.BAT 文件的错误:
首先用这份代码创建一个 Windows 控制台应用程序,把可以把它生成的可执行文件改名为 error_check.exe ,复制到和 APP.BAT 的同一目录下,
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <list>
char default_name[]="APP.BAT";
using namespace std;
int main(int argc,char *argv[])
{
char* name;
if(argc>1){
name=argv[1];
cout<<"文件名参数:"<<name<<endl;
}
else
name=default_name;
ifstream fi(name, ios::_Nocreate); // 不创建打开
if(!fi.is_open()){
cout<<"文件读打开失败"<<endl;
return 1;
}
// 读取文件到内存中
typedef list<string> LineList;
LineList list;
for(string line; getline(fi,line);){
//line.search
list.push_back(line); // 加入链表
}
bool shouldModify = false;
string subStr("fromelf.exe");
// 因为该 BAT 文件是 Keil 自动生成的,
// 错误只在最后一行,所以这里可以
// 只检查最后一个字符串的语法
string& s = list.back();
auto pos = s.find(subStr);
if(pos!=-1){
if((s.at(0)!='"')&&(s.at(pos+subStr.length())!='"')){
cout<<"find a syntax error :"<<endl
<<"\t"<<s<<endl
<<"\t"<<"missing \""<<endl;
shouldModify = true;
const char *quote = "\"";
s.insert(pos+subStr.length(), quote);
s.insert(0,quote);
cout<<"auto modify :"<<endl
<<"\t"<<s<<endl;
}
}
fi.close();
if(shouldModify){ // 如果需要修改文件,就把 list 的内容重新写入文件
ofstream fo(name, ios::_Nocreate); // 不创建打开
if(!fo.is_open()){
cout<<"文件写打开失败"<<endl;
return 1;
}
for(auto i=list.begin(); i!=list.end(); i++){
fo<<*i<<endl;
}
fo.close();
}
}
然后在 APP.BAT 的那个目录下,新建一个 arm_build.BAT 文件,文件内容为
error_check.exe
APP.BAT
其实很简单,就是调用 error_check.exe 去检查和修改 APP.BAT 的错误,然后再打开 APP.BAT 调用编译器。
然后再修改 visual studio 的外部工具里的设置就行了,不直接用 mdk 生成的 APP.BAT 了,改成自己写的 arm_build.bat
这样就不用每次用 keil 重新 build 以后又手动改错误了
用 KEIL 生成的 BAT 文件效率比较低,每次都要全部重新编译,我有点觉得他们是故意这样做的 = = |