Question

I'm using an STM32 microcontroller with minimal libraries attached. I'd like to use the clock() function from <ctime> (and potentially the new std::chrono) but I'm stuck at clock() returning -1.

This isn't surprising, since I don't expect the libraries in gcc-arm-none-eabi to know the peripheral layout of my microcontroller.

How do I tell clock where it gets its tick count from? Can I simply redeclare it, or is there a lower-level function that I need to implement?

Was it helpful?

Solution

This is normally part of the job of porting a libc implementation to a new platform. When you compile a copy of glibc or newlib (the two most popular implementations of the C standard library) you have to provide a series of stub methods, one of these will be providing the time. gcc-arm-none-eabi is a target predefined in newlib that implements a lot of these stubs, but not the ones for getting the time, because like you said these are application specific.

The best thing to do would be to build the toolchain yourself, implementing this method. You can follow the instructions here, but just before you build newlib edit the target to fill in this stub. A good reference to implementing the stubs is available here.

Alternatively you could implement your own clock function directly, when you link your application it will prefer your version over the one in the library. Be warned, however, this means that anything in the library that calls clock will still call the broken library version, so you may need to reimplement a lot of functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top