c++ print executed code - c++

Is there any way to print to a text file the code that it's being executed for debugging purposes?
for example:
if (i == 1)
{
a = true;
}
else
{
a = false
}
So when i = 1 we print to a text file:
if (i == 1)
{
a = true;
}
else
and when i != 1 we print to the text file
if (i == 1)
else
{
a = false
}
I am not saying that this is a good practice. I know that gdb and other tools are much better to debug code so please don't get mad if you think that it's an awful idea. I was just wondering if it can be done. It would be like adding a printf after every line so we only print the lines that get executed. No thread save or anything like that.

I think what you want hasn't anything to do with debugging in the first place, but with unit testing and test coverage:
You'll need to create unit tests (e.g. using googletest) for your code and compile it with code coverage options switched on (e.g. --coverage for GCC). Then you can use a tool to create a coverage report (e.g. lcov/genhtml for the mentioned toolchain).
The unit tests will control the input for your cases (i = 1/0).

For debugging purposes I would say it is not practical. Yes, you can do a printf before/after each line of execution, but that would just clog up your program. Also, if you're talking about debugging the execution of loops, you will end up printing a bunch of junk over and over again and would have to look forever to find potential bugs. In short, use breakpoints.
However, from a theoretical standpoint, it is possible to create a program that outputs itself. This is a little different from what you want because you only need parts of your program, but my best guess is that with a little modification it can be done.

Related

How to best make my catch2 CHECK() output more informative about what it checks?

I am working on some code with unit tests using catch2 (and it will stay that way, for reasons).
Now, in the set of unit tests, there are a lot of (pairs of) lines which look like this:
T t1;
t1 = foo(some, params, here);
CHECK(my_compare(t1, T{some_literal}));
so, my_out_param is being set using a single function call, and then it's compared to a T literal.
Now, when this runs and fails, I get:
/path/to/test.cpp:493: Failure:
CHECK(my_compare(t1, T{some_literal}));
with expansion:
false
but obviously I don't get the "some, params, here". Well, I need it. Otherwise, I don't really know which test failed without reading the source code.
Since there's a reliance on macros here, I can't just wrap CHECK() in a function and do something fancy inside.
What would you suggest I do to make "some, params, here" get printed alongside "some_literal" when the check fails, while:
Keeping my test source code terse.
Not repeating myself
Still getting a valid file and line number
?
Note: The currently-used version of catch2 is 2.7.0, merged into a single header. If a version change would help, that may be doable.
Use the CAPTURE or INFO logging macros (see https://github.com/catchorg/Catch2/blob/devel/docs/logging.md#streaming-macros).
CAPTURE(some);
CAPTURE(params);
CAPTURE(here);
or
INFO("Params: some="<<some<<", params="<<params<<", here="<<here);
should do the trick.
BTW CAPTURE only logs variables that were captured in the same section as the failed test. Example:
SECTION("foo"){
int i = 1;
CAPTURE(i);
CHECK(i==1);
}
SECTION("bar"){
int j = 2;
CAPTURE(j);
CHECK(j==1);
}
outputs
foo.cpp:10: FAILED:
CHECK( j==1 )
with expansion:
2 == 1
with message:
j := 2

Why would a PyDev breakpoint on a return statement only work part of the time?

I have some code that calculates the price of a stock option using Monte Carlo and returns a discounted price. The final few lines of the relevant method look like this:
if(payoffType == pt.LongCall or payoffType == pt.LongPut):
discountedPrice=discountedValue
elif(payoffType == pt.ShortCall or payoffType == pt.ShortPut):
discountedPrice=(-1.0)*discountedValue
else:
raise Exception
#endif
print "dv:", discountedValue, " px:", discountedPrice
return discountedPrice
At a higher level of the program, I create four pricers, which are passed to instances of a portfolio class that calls the price() method on the pricer it has received.
When I set the breakpoint on the if statement or the print statement, the breakpoints work as expected. When I set the breakpoint on the return statement, the breakpoint is interpreted correctly on the first pass through the pricing code, but then skipped on subsequent passes.
On occasion, if I have set a breakpoint somewhere in the flow of execution between the first pass through the pricing code and the second pass, the breakpoint will be picked up.
I obviously have a workaround, but I'm curious if anyone else has observed this behavior in the PyDev debugger, and if so, does anyone know the root cause?
The issues I know of are:
If you have a StackOverflowError anywhere in the code, Python will disable the tracing that the debugger uses.
I know there are some issues with asynchronous code which could make the debugger break.
A workaround is using a programmatic breakpoint (i.e.: pydevd.settrace -- the remote debugger session: http://www.pydev.org/manual_adv_remote_debugger.html has more details on it) -- it resets the tracing even if Python broke it in a stack overflow error and will always be hit to (the issue on asynchronous code is that the debugger tries to run with untraced threads, but sometimes it's not able to restore it on some conditions when dealing with asynchronous code).

Fastest way to make console output "verbose" or not

I am making a small system and I want to be able to toggle "verbose" text output in the whole system.
I have made a file called globals.h:
namespace REBr{
extern bool console_verbose = false;
}
If this is true I want all my classes to print a message to the console when they are constructing, destructing, copying or doing pretty much anything.
For example:
window(string title="",int width=1280,int height=720):
Width(width),Height(height),title(title)
{
if(console_verbose){
std::cout<<"Generating window #"<<this->instanceCounter;
std::cout<<"-";
}
this->window=SDL_CreateWindow(title.c_str(),0,0,width,height,SDL_WINDOW_OPENGL);
if(console_verbose)
std::cout<<"-";
if(this->window)
{
this->glcontext = SDL_GL_CreateContext(window);
if(console_verbose)
std::cout<<".";
if(this->glcontext==NULL)
{
std::cout<<"FATAL ERROR IN REBr::WINDOW::CONSTR_OPENGLCONTEXT: "<<SDL_GetError()<<std::endl;
}
}
else std::cout<<"FATAL ERROR IN REBr::WINDOW::CONSTR_WINDOW: "<<SDL_GetError()<<std::endl;
if(console_verbose)
std::cout<<">done!"<<endl;
}
Now as you can see I have a lot of ifs in that constructor. And I REALLY dont want that since that will slow down my application. I need this to be as fast as possible without removing the "loading bar" (this helps me determine at which function the program stopped functioning).
What is the best/fastest way to accomplish this?
Everying in my system is under the namespace REBr
Some variants to achieve that:
Use some logger library. It is the best option as it gives you maximum flexibility and some useful experience ;) And you haven't to devise something. For example, look at Google GLOG.
Define some macro, allowing you to turn on/off all these logs by changing only the macro. But it isn't so easy to write such marco correctly.
Mark your conditional flag as constexpr. That way you may switch the flag and, depending on its value, compiler will optimise ifs in compiled program. But ifs will still be in code, so it looks kinda bulky.
Anyway, all these options require program recompilation. W/o recompilation it is impossible to achieve the maximum speed.
I often use a Logger class that supports debug levels. A call might look like:
logger->Log(debugLevel, "%s %s %d %d", timestamp, msg, value1, value2);
The Logger class supports multiple debug levels so that I can fine tune the debug output. This can be set at any time through the command line or with a debugger. The Log statement uses a variable length argument list much like printf.
Google's logging module is widely used in the industry and supports logging levels that you can set from the command line. For example (taken from their documentation)
VLOG(1) << "I'm printed when you run the program with --v=1 or higher";
VLOG(2) << "I'm printed when you run the program with --v=2 or higher";
You can find the code here https://github.com/google/glog and the documentation in the doc/ folder.

Debugging C++ in an Eclipse-based IDE - is there something like "step over loop/cycle"?

At the moment I'm using an eclipse-like IDE and the corresponding debug perspective, that most of you are probably familiar with. While debugging code I quite often find myself stepping through many lines of code and observing variables and double checking if everything is as it is supposed to be.
But suppose there is something like this:
1. important line, e.g. generating a new object;
2. another important line, e.g. some tricky class method;
3. for (int i = 0; i < some_limit; ++i)
4. some_array[i]++;
5. more important stuff;
Obviously I'm interested in what happens in lines 1,2 and 5 (I know this is a poor example, but please bear with me for a little while longer) but I don't want to step through all hundreds (or even thousands) of iterations of lines 3/4.
So, finally, my question: Is there some way to step directly over the for-cycle? What I do right now is set a new breakpoint at line 5 and let the program run as soon as I hit line 3 and I believe this is not an optimal solution.
edit: The eclipse implementation of what ks1322 proposed is called "Run to line" and is mapped to ctrl-r
Use until command instead of next.
From gdb documentation:
Continue running until a source line past the current line, in the
current stack frame, is reached. This command is used to avoid single
stepping through a loop more than once.
If you will use until instead of next, gdb will step over loops only once, which almost exactly what you want.

Set Visual Studio (conditional) breakpoint on local variable value

I'm trying to debug a method which among other things, adds items to a list which is local to the method.
However, every so often the list size gets set to zero "midstream". I would like to set the debugger to break when the list size becomes zero, but I don't know how to, and would appreciate any pointers on how to do this.
Thanks.
Why not use conditional breakpoints?
http://blogs.msdn.com/saraford/archive/2008/06/17/did-you-know-you-can-set-conditional-breakpoints-239.aspx
in C#
if(theList.Count == 0){
//do something meaningless here .e.g.
int i = 1; // << set your breakpoint here
}
in VB.NET
If theList.Count = 0 Then
'do something meaningless here .e.g.
Dim i = 1; ' << set your breakpoint here
End If
For completeness sake, here's the C++ version:
if(theList->Count == 0){
//do something meaningless here .e.g.
int i = 1; // << set your breakpoint here
}
I can give a partial answer for Visual Studio 2005. If you open the "Breakpoints" window (Alt + F9) you get a list of breakpoints. Right-click on the breakpoint you want, and choose "Condition." Then put in the condition you want.
You have already got both major options suggested:
1. Conditional breakpoints
2. Code to check for the wrong value, and with a breakpoint if so happens
The first option is the easiest and best, but on large loops it is unfortunately really slow! If you loop 100's of thousands iterations the only real option is #2. In option #1 the cpu break into the debugger on each iteration, then it evaluates the condition and if the condition for breaking is false it just continiues execution of the program. This is slow when it happens thousands of times, it is actually slow if you loop just 1000 times (depending on hardware of course)
As I suspect you really want an "global" breakpoint condition that should break the program if a certain condition is met (array size == 0), unfortunately that does not exist to my knowledge. I have made a debugging function that checks the condition, and if it is true it does something meaningless that I have a breakpoint set to (i.e. option 2), then I call that function frequently where I suspect the original fails. When the system breaks you can use the call stack to identify the faulty location.