#RaspberryPi0 bare metal C++ (mostly working)

I’ve been able to get my Crunky “unikernel” to compile C++. It has stdlib working (string, vectors, etc), class initialisation, and so forth. The big sticking point is exceptions. You can throw exceptions, but it will cause a crash.

Linking libraries together is a bit of a dark art. You need to select a library and link everything in the right order. I’ve mostly used the newlib nano library. But I also link against a gnu stdlib, which seems to provide exceptions, but I’m wondering if I’ve linked against some kind of Linuxism.

So far I’ve assumed that I need something like newlib nano for bare-metal programming. Maybe the full newlib is what I’m after. Documentation seems a little sparse on how to enable it, though.

It’s not a pressing matter. So here is some example code:

#include <uart0.h>
#include <stdio.h>

#include <string>
#include <vector>

class Foo {
		void hi();
		int meaning = 42;

	puts("Foo created");

	puts("Foo being destroyed");

void Foo::hi()
	printf("foo says hi, and notes that the meaning of life is %d\n", meaning);

void test_foo()
	Foo foo;

void test_throw()
#if 0	 // causes crash.
	try {
		throw 20;
		std::vector<int> vec;
		puts("this is never printed");
	} catch(int e) {
		printf("Caught int exception\n");
	} catch (std::exception& e) {
		printf("Caught exception.\n");

extern "C" void kernel_main(void)

	Foo foo();

	puts("C++ test 2");

	std::string str("my string");
	printf("std::string is %s\n", str.c_str());

	puts("I will now echo what you type");
	while (1) {
		char c = getchar();
		//if(c=='\r') uart_send('\n'); // prolly needs linefeed

I’m quite chuffed with this, as it means that I can use C++ on bare metal (with a heavy caveat about exceptions).

You can find the code here.


About mcturra2000

Computer programmer living in Scotland.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s