I am currently writing an R package and using compiled C++ code through the Rcpp
package in R (Rcpp makes the interaction of R and C++ code easier for a non-programmer like me, IMHO).
I want to debug a few errors in my C++ program using gdb. I have googled and found mainly a few resources on debugging R within emacs, R-FAQ, a few mails here, and definitely the R's Writing R Extension Manual.
However, I am doing this for the first time, I could not go too far. Could anyone give me a few pointers on how to debug R packages (or extensions with C++/C code) within emacs. Specifically, I want to take advantages of using ESS with R and gdb with Emacs (as the R-FAQ talks about).
Please note, I am ok on how to use gdb using only C or C++ programs. But I could not translate this knowledge to using gdb with R and extensions.
Emacs provides a special interface to GDB, which uses extra Emacs windows to display the state of the debugged program. See GDB Graphical Interface. Emacs also has a built-in debugger for Emacs Lisp programs.
To execute one line of code, type "step" or "s". If the line to be executed is a function call, gdb will step into that function and start executing its code one line at a time. If you want to execute the entire function with one keypress, type "next" or "n".
You can leverage your existing knowledge of debugging C++ programs by turning the problem into a pure C++ development and debugging task using RInside (a great companion to Rcpp).
Write a main()
C++ function that creates an R instance using RInside, executes R code (or sources an R script) that sets up the test case, and then call the function under test from main(), e.g.
#include <Rcpp.h>
#include <RInside.h>
#include "function_under_test.h"
int main(int argc, char *argv[])
{
using namespace std;
using namespace Rcpp;
RInside R(argc, argv);
string evalstr = R"(
a <- matrix(c(1,1,1, 1,1,1, 1,1,1), nrow = 3, ncol=3)
)";
R.parseEvalQ(evalstr);
SEXP a = R["a"];
R["b"] = function_under_test(a);
evalstr = R"(
print(b)
)";
R.parseEvalQ(evalstr);
return 0;
}
Then proceed as usual when debugging a C++ program with gdb by setting breakpoints in function_under_test()
etc.
This way you avoid switching between R and C++ development environments and having to re-install the R package.
It's not all that easy, unfortunately. You need to jump between ESS, gdb (ie gud in Emacs) and R. The best description is probably still win Writing R Extensions, however there was a recent thread on the ESS mailing list that discusses this too (and note that some replies came in outside the thread so do look at the mailing list archive too).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With