John Behm
John Behm

Reputation: 101

How to check at compile time, whether the C++Standard Library(STL) is supported

I'm abstracting the interrupt handling on multiple microcontrollers. The ARM Cortex M-3/4 ones do greatly support the STL, but the ATMega328p (which are greatly used) do not support the C++ STL. I'd like to still offer the possibility to register callbacks for specific interrupts utilizing the std::function additionally to the basic C-style function pointer. I haven't tested it yet, but was told that the C++ lambdas can do a lot of stuff compared to the simple function pointers, especially when it comes to capturing variables and references.

I'd like to change the defining header class(if necessary) and the implementing classes(if necessary, might not be necessary, because the implementation will simply be missing) in order to remove the member function definition at compile time depending on whether the controller supports or doesn't support the STL. I was wondering if C++ offers such a test or if it's somehow possible to do this by including an STL header and somehow test, whether the include failed or not?

...

#include <functional>

class InterruptVectorTable
{
    bool setCallback(ValueType InterruptNumber, void (*Callback)(void));
    bool setCallback(ValueType InterruptNumber, std::functional<void(void)> Callback);
}

If both definitions are not allowed at the same time, then I'd like to preferably use the std::function.

Upvotes: 1

Views: 764

Answers (1)

mdavezac
mdavezac

Reputation: 515

The new C++17 standard has the __has_include functionality you are looking for. However, it is a bit of a chicken and the egg problem. If your platform does not support STLs then it is likely to be to out of date for c++17.

Instead you likely want to rely on a your build system. For instance, cmake can detect which C++ standard a compiler honors, or even which part of a standard is implemented.

In your case, it might be simpler to have the build define an ad-hoc pre-processor constant HAS_STD_CPP if the standard lib is available on that platform, and then use the c preprocessor to include the STL bits or not, as illustrated in https://en.wikipedia.org/wiki/C_preprocessor.

Upvotes: 5

Related Questions