c++ - 从 C++ 源文件创建全局变量列表

标签 c++ linux ctags nm

我现在正在处理问题,它的语句 - 生成包含 .CPP 文件中所有已声明全局变量列表的文本文件。

我想到了几个想法,第一个:

尝试使用ctags,所以我写了一些简短的脚本:

while read line
do
echo $line
printf "%s" $line >> report.txt
ctags -x --c++-kinds=v --file-scope=no "{$line}" | sort | sed "/const/d" | awk '{printf " %s", $1}' >> report.txt
printf "\n" >> report.txt
done < cpp_source_file_list.txt

这段代码从 cpp_source_file_list.txt 获取 .cpp 源文件的文件名,扫描它的全局变量(忽略常量)并写入报告“文件名[变量列表]。 我遇到的主要问题是 ctags 在某些情况下忽略 STL 类型的行为非常奇怪。

例如,它可以排除“vector v;”之类的行,但包括“std::vector v;”。

有什么办法可以解决这个问题吗?尝试使用 ctags -I ./id.txt 附加键并手动制作要覆盖的标识符列表,但它也会带来不正确的结果。

第二种方式:

使用 nm 命令,例如:

nm builtsource.o | grep '[0-9A-Fa-f]* [BCDGRS]'

但在这种情况下,我会收到不必要的信息,例如:

0000000000603528 B M 
0000000000603548 B N 
0000000000603578 B _ZSt3cin@@GLIBCXX_3.4 <- (!)
0000000000603579 B _ZSt4cout@@GLIBCXX_3.4 <- (!)
0000000000603748 B t 

现在我不知道如何改进其中一种方法来从任意 .cpp 源文件中接收有关声明的全局变量列表的正确信息。我很乐意听到关于这个问题的任何建议。

最佳答案

您可以利用 Doxygen实现这一点。 Doxygen 可以解析 C++ 文件并生成一个 XML 文件,该文件捕获文件中遇到的所有变量。具体来说,如果您设置以下配置选项:

EXTRACT_ALL= YES
GENERATE_TAGFILE= doxygen.tag

给定一个输入文件,如:

#include <vector>

using namespace std;

std::vector<int> s1;
vector s2;

您可以生成具有以下内容的输出 doxygen.tag 文件:

<?xml version='1.0' encoding='ISO-8859-1' standalone='yes' ?>
<tagfile>
  <compound kind="file">
    <name>input.cpp</name>
    <path>C:/Users/haney/tmp/tmp55/</path>
    <filename>input_8cpp</filename>
    <namespace>std</namespace>
    <member kind="variable">
      <type>std::vector&lt; int &gt;</type>
      <name>s1</name>
      <anchorfile>input_8cpp.html</anchorfile>
      <anchor>93b3bd32f5b6bff31bc4052716ddd444</anchor>
      <arglist></arglist>
    </member>
    <member kind="variable">
      <type>vector</type>
      <name>s2</name>
      <anchorfile>input_8cpp.html</anchorfile>
      <anchor>8feb4a508135e43a72f227568b755a07</anchor>
      <arglist></arglist>
    </member>
  </compound>
  <compound kind="namespace">
    <name>std</name>
    <filename>namespacestd.html</filename>
  </compound>
</tagfile>

获得 XML 文件后,您应该能够提取出您要查找的信息。

关于c++ - 从 C++ 源文件创建全局变量列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8909755/

相关文章:

linux - 使用部分名称搜索用户

python - 查找 vim 的 virtualenv 当前包目录

c++ - 如何在main()中调用构造函数?

c++ - 使用CMake添加C++编译器标志

linux - 在 Linux 中创建_singlethread_workqueue

linux - 是否可以链接 16 位代码和 32 位代码?

c++ - 将字符串数据附加到 std::vector<std::byte>>

c++ - cmake 命令找不到 boost 库

ctags - ctags命令不会递归说 “it is not a regular file”

c# - C# 的 Vim omnicompletion