ARM: Adding C++ Cout to a project
Information in this knowledgebase article applies to:
I have some C++ files in my project and would like to use cout (console output). I have printf working but when I try to add cout to my initialization code in main(), my program doesn’t make it to main(). I have the extern “C” wrapper around my code in main.cpp and have “using namespace std;” in the main.cpp module. I am using the CMSIS RTX RTOS and a cortex M4 processor. What am I doing wrong?
The most likely cause is you have not allocated enough Heap and Stack memory for the cout library functions
First, you must increase the Heap space in the “startup_xxx.s” file. Without cout, the heap space used in a simple test project was 29 bytes. Adding cout to the project required 1754 bytes of heap in the test project. As a result, the heap should be increased to at least 0x800 bytes in the startup file. The main stack requirements are also a little larger when using cout. The main stack without cout used 120 bytes while the main stack requirement with cout was 632 bytes. So, the recommended stack size setting in the startup file would be at least 0x400 bytes.
In addition to increasing the main stack and heap, the stack for the task calling cout also needs to be increased. Just calling printf from the main task requires 312 bytes in a simple project. Adding cout increased the main stack requirements to 1504 bytes. As a result, it is recommended to increase the task stack in the RTX_Config_CM.c file to 2000 bytes minimum for the tasks that are calling cout.
Other things to look at include making sure that the iostream and stdout.h includes are outside the extern “C” wrapper.
These recommendations should work with any of the retargeted standard out interfaces including USART/UARTs, ITM, and the Event Recorder.
Last Reviewed: Tuesday, August 1, 2017
of your data.