Skip to content
Prev 393414 / 398500 Next

Adding comment in C++ code for debugging purpose

?s 13:38 de 17/12/2022, Christofer Bogaso escreveu:
Hello,

1. Forget R_print, it is meant for C code, not for Rcpp.
    Besides, it is also an error of mine, I was thinking about Rprintf, 
see below.

2. The following works as expected.
    It's the first example in

vignette("Rcpp-introduction", package = "Rcpp")

    with the if/Rcout and Rprintf instructions added.



File: convolve_rcpp.cpp



#include "Rcpp.h"

using namespace Rcpp;
// [[Rcpp::export]]
NumericVector convolve_cpp(const NumericVector& a, const NumericVector& b) {
   // Declare loop counters, and vector sizes
   int i, j,
	na = a.size(), nb = b.size(),
	nab = na + nb - 1;
	// Create vector filled with 0
	NumericVector ab(nab);
	// Crux of the algorithm
	for(i = 0; i < na; i++) {
		// this works as expected, it prints to the console
		// printing is on every 10 times through the loop
		if(i % 10 == 0)  {
			Rcpp::Rcout << "Some Value " << i << "\n";
			Rcpp::Rcout << "     Value " << a[i] << std::endl;
		}
		for(j = 0; j < nb; j++) {
			ab[i + j] += a[i] * b[j];
		}
	}
	Rprintf("Done\n");
	// Return result
	return ab;
}



Then run the R script


path <- "~/path/to/Rcpp/code"
fl <- list.files(path, pattern = "convolve\\.cpp")
fl <- file.path(path, fl)

Rcpp::sourceCpp(fl)

x <- 1:1e4
y <- 10:1

z <- convolve_cpp(x, y)
str(z)
# num [1:10009] 10 29 56 90 130 175 224 276 330 385 ...


Hope this helps,

Rui Barradas