问题
i got a problem about how to write a clang plugin that will change the code. i want inject some code to the program,just like this:enter code here
//the original code
//the filename is user_code.cpp
int f1(){
return 1;
}
int f2(){
return 2;
}
int f3(){
return 3;
}
int main(){
for(int i=0;i<1000;i++)f1();
for(int i=0;i<10000;i++)f2();
for(int i=0;i<100000;i++)f3();
return 0;
}
//the injected code
int function_counter[3];
int f1(){
function_counter[0]++;
return 1;
}
int f2(){
function_counter[1]++;
return 2;
}
int f3(){
function_counter[2]++;
return 3;
}
int main(){
for(int i=0;i<1000;i++)f1();
for(int i=0;i<10000;i++)f2();
for(int i=0;i<100000;i++)f3();
return 0;
}
now, i can do this by parsing this code to an AST.and traverse it, use ReWriter class to modify the code,at last rewrite the modified code to a new file.but this is not transparent to user.i want write a clang plugin,user just input the command:
clang -load myplugin.so -plugin myplugin user_code.cpp -o user_code.o
the code first can be injected transparently,and then compile like usualy.what can i do?any suggest?
来源:https://stackoverflow.com/questions/19346660/how-to-write-a-clang-plugin-to-inject-some-code-to-the-original-code-while-compi