c->再次封装已有函数的快速方法

在C代码开发中,有时想清楚项目中调用特定函数的所有位置,可以借用几条shell指令轻松搞定。

比如要弄清项目中的所有调用system函数的位置及其调用参数:

Step1: 把项目中的所有源代码的system函数替换成SYSTEM_FUN

grep "system(" -R | awk -F: '{print $1}'|sort -u |xargs sed -i "s/system(/SYSTEM_FUN(/g"

Step2: 找一个公共的头文件,定义SYSTEM_FUN

#define SYSTEM_FUN(str)   system_fun(__FILE__, __FUNCTION__, __LINE__, str)  

Step3:再次封装system,需注意与原函数的返回参数一致
int system_fun(const char *file, const char *function, int line, char *command){
    tcdbg_printf("[%s,%s,%d]%s\n", file, function, line, command);
    int ret = system(command);
    return ret;
}

 

再比如弄清含有可变参数的函数sysmgr_getint的调用位置:

int sysmgr_getint(char *xpath, ...);

Step1:全部替换成SYSMGR_GETINT
grep " sysmgr_getint (" -R | awk -F: '{print $1}'|sort -u |xargs sed -i "s/ sysmgr_getint (/SYSMGR_GETINT (/g"
Step2:找一个公共的头文件加一个宏定义
#define SYSMGR_GETINT(args...) sysmgr_getint_fun(__FILE__,__FUNCTION__,__LINE__,##args)
Step3:再次封装原函数,需注意与原函数的返回参数一致
int sysmgr_getint_fun(const char *file, const char *func, int line, char *xpath, ...)
{
    int ret = 0;
    char tmp_path[1024] = {0};
    va_list ap;
 
    va_start(ap, xpath);
    vsnprintf(tmp_path, sizeof(tmp_path), (char *)xpath, ap);
    va_end(ap);
 
    ret = sysmgr_getint(tmp_path);
    printf("[%s,%s,%d] %d sysmgr getint (%s)\n", file, func, line, ret, tmp_path);
    return ret;
}

posted on 2019-12-27 15:11  LiveWithACat  阅读(326)  评论(0编辑  收藏  举报