Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ macro to log every line of code

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?

like image 369
Karthick S Avatar asked Sep 19 '11 09:09

Karthick S


People also ask

What is __ LINE __ in C?

__LINE__ is a preprocessor macro that expands to current line number in the source file, as an integer. __LINE__ is useful when generating log statements, error messages intended for programmers, when throwing exceptions, or when writing debugging code.

What is __ file __ in C?

__FILE__ This macro expands to the name of the current input file, in the form of a C string constant. This is the path by which the preprocessor opened the file, not the short name specified in ' #include ' or as the input file name argument. For example, "/usr/local/include/myheader.

What is __ function __ in C++?

(C++11) The predefined identifier __func__ is implicitly defined as a string that contains the unqualified and unadorned name of the enclosing function. __func__ is mandated by the C++ standard and is not a Microsoft extension.

What is macro in C?

A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro. Macro definitions need not be terminated by a semi-colon(;).


1 Answers

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.

like image 125
rounin Avatar answered Oct 04 '22 02:10

rounin