Linux人必看:读代码,找定义

daocaoren0827 2013-08-02 03:02:42
作为powerlinux系统测试人员,经常会遇到要通过阅读代码查找问题的情况。在linux上大家一般会使用ctags与vim或emacs结合进行代码阅读。本文介绍一个找出预编译指令分支中所有函数定义的小心得。

ctags会生成一个代码中函数、变量等等标识符的索引文件。vim/emacs根据此文件可以很快地跳到相关函数、变量的定义处。这大大方便了代码的阅读。linux kernel的为此专门提供了“tags”这个target来生成kernel的ctags索引文件。如

nutlp1:/usr/src/linux-3.0.76-0.11 # make tags
GEN tags


然后用vim打开一个源文件,把光标移到想要查找其定义的函数/变量上,按“g+ctrl+]”,如果该标识符有唯一定义,vim就会自动跳到那里。否则vim会列出所有的位置让用选择。

但是最近遇到了一个特别的情况。
#ifdef CONFIG_HAVE_MEMORYLESS_NODES

/*
* N.B., Do NOT reference the '_numa_mem_' per cpu variable directly.
* It will not be defined when CONFIG_HAVE_MEMORYLESS_NODES is not defined.
* Use the accessor functions set_numa_mem(), numa_mem_id() and cpu_to_mem().
*/
DECLARE_PER_CPU(int, _numa_mem_);

#ifndef set_numa_mem
static inline void set_numa_mem(int node)
{
percpu_write(_numa_mem_, node);
}
#endif

#ifndef numa_mem_id
/* Returns the number of the nearest Node with memory */
static inline int numa_mem_id(void)
{
return __this_cpu_read(_numa_mem_);
}
#endif

#ifndef cpu_to_mem
static inline int cpu_to_mem(int cpu)
{
return per_cpu(_numa_mem_, cpu);
}
#endif

#ifndef set_cpu_numa_mem
static inline void set_cpu_numa_mem(int cpu, int node)
{
per_cpu(_numa_mem_, cpu) = node;
}
#endif

#else /* !CONFIG_HAVE_MEMORYLESS_NODES */

#ifndef numa_mem_id
/* Returns the number of the nearest Node with memory */
static inline int numa_mem_id(void)
{
return numa_node_id();
}
#endif

#ifndef cpu_to_mem
static inline int cpu_to_mem(int cpu)
{
return cpu_to_node(cpu);
}
#endif
复制代码
想查找numa_mem_id的定义,这里有两个不同的定义,分别在各自不同的预编译分支中。vim只把我带到了第一个定义处,但实际上系统使用的是恰恰是第二个定义。

这是因为ctags生成的索引使用一个vim中的搜索命令来标识位置:
$ grep numa_mem_id tags
numa_mem_id include/linux/topology.h /^static inline int numa_mem_id(void)$/;" f


此处的“/^static inline int numa_mem_id(void)$/”便是。这样作的好处是即便源文件有了些许的增减,不用重新构筑索引,还是能找到定义。坏处就是处理不了这种在同一个文件中有两个定义的情况。

全部内容点击查看
...全文
236 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

742

社区成员

发帖
与我相关
我的任务
社区描述
该论坛主要探讨Linux系统在IBM Power平台的安装、部署、应用开发等话题,并为网友们提供自由交流的平台。
社区管理员
  • Power Linux社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧