Home > Backend Development > C++ > How can I generate a call graph for C code to visualize execution paths?

How can I generate a call graph for C code to visualize execution paths?

Patricia Arquette
Release: 2024-12-01 01:41:12
Original
303 people have browsed it

How can I generate a call graph for C   code to visualize execution paths?

Generating a Call Graph for C Code to Visualize Execution Paths

To generate a calling graph for C code, we aim to uncover all potential execution paths that lead to a specific target function. This can be beneficial in eliminating the manual identification of every path, especially when multiple paths exist.

In the provided example, the target function is D. To achieve this, we can use the following steps:

static void D() {}
static void Y() { D(); }
static void X() { Y(); }
static void C() { D(); X(); }
static void B() { C(); }
static void S() { D(); }
static void P() { S(); }
static void O() { P(); }
static void N() { O(); }
static void M() { N(); }
static void G() { M(); }
static void A() { B(); G(); }

int main() {
  A();
}
Copy after login

Once we have our code, we can generate the call graph using the following commands:

$ clang++ -S -emit-llvm main1.cpp -o - | opt -analyze -dot-callgraph
$ dot -Tpng -ocallgraph.png callgraph.dot
Copy after login

This will produce a visual representation of the call graph.

However, to obtain the actual function names rather than their mangled counterparts, we can postprocess the graph using c filt:

#include <vector>

struct A { 
  A(int);
  void f(); // not defined, prevents inlining it!
};

int main() {
  std::vector<A> v;
  v.push_back(42);
  v[0].f();
}

$ clang++ -S -emit-llvm main1.cpp -o - |
 opt -analyze -std-link-opts -dot-callgraph
$ cat callgraph.dot | 
 c++filt | 
 sed 's,>,\>,g; s,-\>,->,g; s,<,\<,g' | 
 gawk '/external node/{id=}  != id' | 
 dot -Tpng -ocallgraph.png    
Copy after login

This will yield a more informative call graph, showing the actual names of the functions and classes involved.

The above is the detailed content of How can I generate a call graph for C code to visualize execution paths?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template