Hello World as C++ project

Hello,

after some hours extensive search, I want to share my findings.

I got very strange reset behaviours in a C++ project on an nRF5340 with nRF Connect SDK 2.1.0.

After stripping down the code, I reproduced the behaviour with the hello_world example. I changed it to C++ and added the function printTest2. 

#include <zephyr/zephyr.h>

bool printTest2() {
	printk("Test2\n");
}


int main(void)
{
	for (;;) {
		printk("Test1\n");
		printTest2();
		k_msleep(500);
	}
	return 0;
}

I know it should return a bool, but actually it does not return anything.

If the project is a pure C-project, it works without problems. 

But if it is C++, the result is as follows:

�*** Booting Zephyr OS build v3.1.99-ncs1 ***
Test1
�*** Booting Zephyr OS build v3.1.99-ncs1 ***
Test1
�*** Booting Zephyr OS build v3.1.99-ncs1 ***
Test1

I would be very thankful if someone could give me an advice why leaving the return away leads to a hard fault.

Many thanks in advance.

Kind regards,

Christian

  • OK, shame on me :-(

    A view at the disassembly showed the different beaviour of the C++ and C compiler.

    The C++ compiler does not restore the stack and PC.

    bool printTest2() {
         42c:	b508      	push	{r3, lr}
    	printk("Test2\n");
         42e:	4801      	ldr	r0, [pc, #4]	; (434 <_Z10printTest2v+0x8>)
         430:	f004 f8a4 	bl	457c <printk>
         434:	00005770 	.word	0x00005770

    Whereas the C compiler restores them even with missing return.

    bool printTest2() {
         42c:	b508      	push	{r3, lr}
    	printk("Test2\n");
         42e:	4802      	ldr	r0, [pc, #8]	; (438 <printTest2+0xc>)
         430:	f004 f896 	bl	4560 <printk>
    }
         434:	bd08      	pop	{r3, pc}
         436:	bf00      	nop
         438:	00005730 	.word	0x00005730

  • In C++, it is Undefined Behaviour to reach end-of-function in a function that does not return void. In other words, you must return something in a non-void function in C++ (unless you have an infinite loop of course, so that the function never returns).

    C is more tolerant. It is not Undefined Behaviour as long as you do not use/read the (undefined) return value.

Related