C++ on Jupyter notebooks

Joseph Hansen
2 min readDec 4, 2017

I just set up an interactive C++ environment and it was awesome.

I often want to quickly “try out” some code, and have recently been needing to do a lot of it with the armadillo linear algebra library. To do so, I have made many clunky little programs and lots of new files, compiling them all by hand in Terminal.

After getting set up with the C++ kernel on Jupyter notebooks, here are my thoughts, and an example:

Learning to code with Python is considerably easier than learning C++ in the standard CS 101 course. You can go from 0 to “hello, world” in no time, without fussing about creating projects; returning 0; or explaining brackets, semicolons or #includes.

Python is a rather interactive language. Intuitive for typing something and seeing the calculated result.

I’m not extolling Python as an argument that it should be taught first. C++ is probably still the right way to go? At least, I’m sure it is in some cases.

C++ is a great software language but it doesn’t have that intuitive characteristic. The question is, can we start with C++ but get the same initial experiences as when a new user picks up Python?

I hope the reader is conjuring up a comparison like this in their head:

#include <iostream>
int main()
{
std::cout << "Hello, world" << std::endl;
return 0;
}

versus:

print("Hello, world")

and the corresponding explanations that ensue for a bunch of CS 101 students.

The heart of that problem affects even experienced programmers, who have probably thought it would be nice to have a cruddy little interactive shell. Sometimes you just need to throw out a line or two of C++ and see what it looks like.

Enter Jupyter notebooks.

Here is an example of the code I wrote as I set it up for the first time. It uses armadillo (C++ linear algebra library).

#pragma cling load("/Users/something/armadillo-8.300.1/include/armadillo")
#include <iostream>
using std::cout;
using std::endl;
using namespace arma;
mat x;
x << 1 << 2 << 3 << endr << 4 << 5 << 6 << endr << 7 << 8 << 9 << endr;
mat y = randn(6,6);
cout << x << endl << y << endl;

Get started at the Github repository page.

--

--

Joseph Hansen

Computer scientist, bibliophile, US soccer fan, BYU + Johns Hopkins alum, jhuapl, qualtrics. https://linktr.ee/JH424