开发者

Search and replace in C source code, without touching comments

I have a lot of c code in which I would like to replace old syntax style with a new style. E.g. the following prefixes "si":

int siName;

should become "i":

int iName;
开发者_运维知识库

But the reg-expression or other find/replace tool, should not touch any source code comments. Any solution?


You can try out coccinelle. It has a bit of a learning curve, but it parses the C code and executes the transformations given to it in a script. For example, for renaming a function from foo to bar, the script would look like this (from here):

@@

@@

-foo()
+bar()

It can probably rename variables based on regular expressions as well, I haven't yet found out a way though.


In vi use

       :%s/\<Oldword\>/Newword/gc

This asks you whether or not to replace a particular occurrence of the whole word which you may happily neglect if it is a part of the comment.


With respect to the suggestion about Coccinelle, you can match using regular expressions using the following notation:

identifier foo =~ "xxx";

That is, foo will match any identifier that contains xxx. PCRE regular expressions are supported.

You can also use python to create a new identifier:

@a@
identifier x;
@@

foo(x)

@script:python b@
x << a.x;
xx;
@@

coccinelle.xx = "%s%s" % (x,x)

@@
identifier a.x;
identifier b.xx;
@@

 foo(
-  x
+  xx
   )

For the program:

int main () {
  foo(one);
}

This gives

int main () {
  foo(oneone);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜