C++ Kernel Guide¶
See also: Assignment Creation and Notebook‑Based Assignments.
Create a basic C++ assignment¶
Tip
Download a starter notebook: Download C++.ipynb
-
Upload the notebook:
- Click the Upload button in the top‑left of the notebook UI
- Select the downloaded file and confirm
-
Open it:
- The file appears in the left panel — double‑click to open
-
Run it to verify everything works
Install and use C++ libraries¶
Open a Terminal:
Install system headers/libraries with apt (example: Boost):
sudo apt-get update sudo apt-get install -y libboost-all-dev
Use the library in the notebook (xeus‑cling style, no main function):
#include <string> #include <boost/algorithm/string/case_conv.hpp> std::string s = "hello c++"; boost::to_upper(s); s // no semicolon to display the value
Note: xeus‑cling is an interpreter. Avoid defining and running a traditional
mainfunction. Prefer interactive cells.Tip: After installing system packages, use Project Save or Stop (which saves automatically) so they persist across restarts.
Gotchas and tips for xeus‑cling¶
Do not define two functions in the same cell (or mix globals and functions)¶
This will raise “function definition is not allowed here”.
Failure example:
int foo() { return 42; } int foo2() { return 43; }
Correction: split across cells
int foo() { return 42; }
int foo2() { return 43; }
Displaying values: omit the semicolon¶
To show a computed value, don’t end the line with ;.
2 * 3
2 * 3;
Namespaces and standard types¶
If you see errors about basic_string, ensure you use std::basic_string or add:
using namespace std;
Redefinition errors¶
If you re‑run a cell that defines the same symbol (variable/function), you’ll get a redefinition error. Use “Kernel → Restart” to clear state when needed.
scanf does not work; use a wrapper¶
scanf is unreliable in this environment. Use this wrapper that leverages std::cin:
#include <stdlib.h> #include <stdarg.h> #include <iostream> #include <string> int scanf_lab(const char* fmt, ...) { std::string input; std::getline(std::cin, input); va_list args; va_start(args, fmt); int ret = vsscanf(input.c_str(), fmt, args); va_end(args); return ret; } int n; scanf_lab("%d", &n); n
Add include and library paths; load shared libraries¶
Add paths:
#pragma cling add_include_path("/root/include") #pragma cling add_library_path("/root/lib")
Load a library:
#pragma cling load("mylibrary") // or .L /root/mylibrary.so
Compile and use a shared object¶
Create files:
a.cpp
int ret0 () { return 0; } int ret1 () { return 1; }
a.h
int ret0 (); int ret1 ();
Compile:
apt-get update && apt-get install -y clang-9 export PATH=/usr/lib/llvm-9/bin:$PATH clang++ -shared -fPIC a.cpp -o a.so
Use in the notebook:
.L /root/a.so #pragma cling add_include_path("/root/") #include <a.h> ret1()