gpt4 book ai didi

c - 将代码添加到函数中

转载 作者:太空宇宙 更新时间:2023-11-04 03:48:51 25 4
gpt4 key购买 nike

我有一个函数:

void srunner_free(SRunner *sr){
.......
}

我想在原始函数体之前添加一些 C 代码,所以它变成了:

void srunner_free(SRunner *sr){
//Some other random code, not necessary printfs, printf is just an example
printf("hello world");

.......
}

我该怎么做呢?我可以使用 grep 等工具来完成吗?

谢谢

最佳答案

您应该能够使用 coccinelle为了这。这是专门用于修改此类源代码的工具。

播放速度非常快,测试输入如下

$ cat test.c

int foo(int i)
{
return i+1;
}

void srunner_free(SRunner *sr)
{
int i;
foo(i);
return;
}

和下面的 coccinelle 脚本

$ cat test.cocci 
@@
typedef SRunner;
statement S;
identifier sr;
@@
void srunner_free(SRunner *sr)
{
...
+ printf("hello world");
S
...
}

结果是

$ spatch -sp_file test.cocci test.c
init_defs_builtins: /usr/share/coccinelle/standard.h
HANDLING: test.c
diff =
--- test.c 2014-03-08 01:34:13.000000000 +0100
+++ /tmp/cocci-output-24589-dfa2db-test.c 2014-03-08 01:34:57.000000000 +0100
@@ -7,7 +7,9 @@ int foo(int i)
void srunner_free(SRunner *sr)
{
int i;
+ printf("hello world");
foo(i);
+ printf("hello world");
return;
}

$

这里的 printf 语句放在每个语句的前面,这并不是您想要的,但结果相差不远。我不确定如何限制我头顶的这种权利,但我想我以前见过这样的例子,所以它应该是可能的。


更新:我今天继续研究这个,修改什么比较容易我最初建议正是想要的解决方案。该脚本现在包含两个规则。

第一条规则只是一条匹配规则,没有进行任何修改。它匹配两个相邻的语句并将位置绑定(bind)到其中的最后一个。所以这个规则将绑定(bind)一个函数内所有语句的位置,除了第一个语句。

然后,第二条规则通过排除规则 1 中某个位置绑定(bind)的任何语句,将 printf 语句(或其他语句)插入到第一条语句的前面。

@rule1@
typedef SRunner;
statement S1, S2;
identifier sr;
position p;
@@
void srunner_free(SRunner *sr)
{
        ...
        S1
        S2@p
        ...
}

// typedefs are actually global, so no need to repeat
// (and doing so would in fact generate an error)
@rule2@
statement S;
identifier sr;
position p != rule1.p;
@@
void srunner_free(SRunner *sr)
{
        ...
+       printf("hello world");
        S@p
        ...
}

关于c - 将代码添加到函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22260118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com