[R] Adding comment in C++ code for debugging purpose
Ivan Krylov
kry|ov@r00t @end|ng |rom gm@||@com
Sat Dec 17 09:23:41 CET 2022
On Sat, 17 Dec 2022 05:02:33 +0530
Christofer Bogaso <bogaso.christofer using gmail.com> wrote:
> I am using an R package where there are some C++ code.
>
> To check some intermediate values generated by that C++ code, I added
> a line like
>
> std::cout << "My values";
A more efficient way of debugging C++ code running under R could be
with the use of a C++ debugger. For example,
0) Make sure you have GDB (or a different debugger, e.g. lldb on a Mac)
installed. You probably do, since you already have a working C++
toolchain.
1) Run R using the command line: R -g gdb. The debugger will start and
wait for your commands. Type: run. This will start R.
2) Type library(YOUR_PACKAGE_NAME) to load the package. You don't have
to do it in this order (GDB can remember to set a breakpoint on a
function that's not yet loaded in the address space), but this way you
can be sure about the name of the function.
3) Press Ctrl-C, sending an interrupt to the application. GDB handles
the interrupt and presents you with its prompt again. Type:
break YOUR_FUNCTION_NAME. If the function name is right, GDB will tell
you that a breakpoint is set. If not, it will ask you whether to
postpone setting a breakpoint until the function shows up. Since the
shared library should have been loaded by this time, the correct answer
would be probably "no".
4) Type: continue. The debugger will give the control back to R. You
can press Enter once and see R print the prompt symbol (">") again. Run
your code that uses the package.
5) Eventually, you'll hit the breakpoint and find yourself in the
debugger again. Like in the R browser, you can use "n" to step line by
line, "s" to step inside function calls, and "c" to continue execution
uninterrupted. You can also use "bt" and "frame NUMBER" to inspect the
call stack and "print EXPRESSION" to see the values of various objects.
A longer guide to GDB can be found at <https://beej.us/guide/bggdb/>.
Telling GDB where the package source code is [*] will ease the process
even further, as would obtaining debugging symbols and the source code
for R itself.
--
Best regards,
Ivan
[*]
https://sourceware.org/gdb/onlinedocs/gdb/Source-Path.html
https://alex.dzyoba.com/blog/gdb-source-path/
More information about the R-help
mailing list