How to use C++ in Jupyter Lab

One of the main extension points of the Jupyter stack is the kernel, the part of the infrastructure responsible for executing the user’s code. Jupyter kernels exist for numerous programming languages. Most Jupyter kernels are implemented in the target programming language: the reference implementation ipykernel in Python, IJulia in Julia

Xeus is a C++ implementation of the Jupyter kernel protocol. It is not a kernel itself but a library that facilitates the authoring of kernels, and other applications making use of the Jupyter kernel protocol.

Interpreted C++ is already a reality at CERN with the Cling C++ interpreter in the context of the ROOT data analysis environment.

As a first example for a kernel based on xeus, the guys from Jupyter have implemented xeus-cling, a pure C++ kernel.

Installation

The first step is to install miniconda using the instructions, in my case I will use a docker container:

docker run -it -p 8889:8888 continuumio/miniconda3 /bin/bash

After the docker starts, we can install C++ support and a jupyter-lab using:

conda install xeus-cling jupyterlab -c conda-forge

Last, let’s start the jupyter-lab

jupyter-lab --ip=* --no-browser --allow-root

We will need the token displayed, and now we connect to our spawned jupyter-lab in the port 8889 (remember that we redirect 8888 to 8889 during docker run to prevent conflict with our existing jupyter.

In the new jupyter, we will see the option to create a new C++11 notebook.

Testing

We can create a new jupyter notebook with C++11 as the kernel and run a hello world program

#include <iostream>

int main() {
    std::cout << "Hello World!";
    return 0;
}
main()
Hello World!
0