Monday, April 07, 2014

Play with C++ code in Rstudio

I am not a C++ programmer but sometimes I need to play with some C++ code. On my Linux workstation, I have the complete GNU tool chain installed. I don't really want to do that on my tiny Windows ultrabook because ... well, it's tiny and I want to keep it that way.

I do have R (and the magical Rcpp package), Rtools, and Rstudio installed on my ultrabook. I just realized how trivial it is to tweak C++ code fragments using these tools together.

For example, in order to run this very simple C++ code fragment:

===========================================
#include <iostream>
using std::cout;

int main() {
for (int hashNum = 1; hashNum <= 5; hashNum++) {
cout << "#";
}
cout << "\n";
return 0;
}
===========================================

One just need to add a few lines so that the code looks like this:

===========================================
#include <Rcpp.h>

using std::cout;
using namespace Rcpp;

// [[Rcpp::export]]
int main() {
  for (int hashNum = 1; hashNum <= 5; hashNum++) {
cout << "#";
}
cout << "\n";
return 0;
}

/*** R
main()
*/
===========================================

Hit Ctrl + Enter, problem solved!

No comments:

Counter