C++ macro to log every line of code

2019-03-12 13:40发布

During one of my recent discussions with my manager, he mentioned that one of his former clients used a C++ macro to log info about every line of code. All they had to do was enable an environment variable before starting the run. (Of course the environment variable was enabled in the test-bed alone.

The log mentioned the variables used and their corresponding values too. For example, for the line:

a = a + b;

The log would say something like:

"a = a + b; (a = 5 + 3)"

Personally, I was not sure if this was possible, but he was very sure of this having existed, though he did not remember the specifics of the code.

So, here is the (obvious) question: Is this possible? Can you provide the code for this one?

2条回答
Ridiculous、
2楼-- · 2019-03-12 14:21

You may check how BOOST_CHECKA from Boost.Test is implemented. Internally it uses expression templates.

For test:

#define BOOST_TEST_MAIN

#include <boost/test/included/unit_test.hpp>
#include <boost/test/test_tools.hpp>

BOOST_AUTO_TEST_CASE(test1)
{
    int a=0;
    int b=1;
    int c=2;
    BOOST_CHECKA( a+b == c );
}

Output is:

Running 1 test case...
main.cpp(11): error: in "test1": check a+b == c failed [0+1!=2]

*** 1 failure detected in test suite "Master Test Suite"

Note values in square brackets: [0+1!=2]

It has some limitations.

For test:

BOOST_CHECKA( (a+b) == c );

output is:

check (a+b) == c failed [1!=2]
查看更多
你好瞎i
3楼-- · 2019-03-12 14:25

I don't know if every line/variable can be expanded like that, but function calls can be logged. I have logged all function calls using the -finstrument-functions option of gcc. It will call:

  void __cyg_profile_func_enter (void *this_fn, void *call_site);

and

   void __cyg_profile_func_exit  (void *this_fn, void *call_site);

for function enter and exit.

The docs explain how to use it. I don't know if other compilers offer something similar.

查看更多
登录 后发表回答