Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Easy Trace of Function Entry and All Exits

3.76/5 (8 votes)
25 May 2021CPOL 6.1K  
A simple struct is presented which permits the automatic display to the console of function entry and all exits
If you need to trace the function entrances and exits of your project, the method presented here makes it easy to do utilizing a simple struct which makes it all automatic.

Introduction

Here is a small C++ struct which makes it easy and effortless to automatically display via the console the entry and exits of your functions. Note that it utilizes the helpful console colors of @Jaded-Hobo previously published Add Color to Console Projects.

C++
struct cpreamble
{
    std::string m_func;
    cpreamble(const char* func) : m_func(func) 
    { std::cout << fg_yellow << func << fg_white << " entry" << std::endl; }
    ~cpreamble() { std::cout << fg_cyan << m_func << fg_white << " exit" << std::endl; }
};
#define PREAMBLE cpreamble _cpreamble(__func__);

So one can utilize it as below:

void foobar()
{
    PREAMBLE // first line in function
    // full body of function ...
}

Voila! The entry and all returns are automatically displayed to the console or wherever you wish if you modify cpreamble via the constructor and destructor of cpreamble. Of course, one can utilize __FUNCSIG__ instead of __func__ as the macro argument if one can tolerate the lengthy class type strings and overly informative function signatures which result. Such lengthy strings can of course be simplified but that is another project and tip. Please note the automatic formatting by Visual Studio of code which follows a macro which contains its own terminating semi-colon does not work as expected but in my own work, I insist on doing so. - Cheerio

History

  • 26th May, 2021: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)