Hm, I spoke too soon. Even when using the latest available compiler, and the correct C++11, 14 or even 17 flags, AVR-GCC/G++ doesn’t give you the <functional> functionality. Or really, any C++ standard library functionality at all.
[env:megaatmega2560]
platform = atmelavr
board = megaatmega2560
framework = arduino
build_flags = -std=gnu++17
build_unflags = -std=gnu++11
platform_packages =
toolchain-atmelavr@1.70300.191015
#include <Arduino.h>
#include <vector>
void setup() {
std::vector<int> vec {1,2,3};
}
void loop(){
}
Results in -std=gnu++17 but no implemented C++ standard library
avr-g++ -o .pio\build\megaatmega2560\src\main.cpp.o -c -std=gnu++17 -fno-exceptions -fno-threadsafe-statics -fpermissive -Os -Wall -ffunction-sections -fdata-sections -flto -mmcu=atmega2560 -DPLATFORMIO=40400 -DARDUINO_AVR_MEGA2560
-DF_CPU=16000000L -DARDUINO_ARCH_AVR -DARDUINO=10808 -Iinclude -Isrc -IC:\Users\Maxi\.platformio\packages\framework-arduino-avr\cores\arduino -IC:\Users\Maxi\.platformio\packages\framework-arduino-avr\variants\mega src\main.cpp
src\main.cpp:2:10: fatal error: vector: No such file or directory
#include <vector>
^~~~~~~~
compilation terminated.
I thought they improved the last time I looked at it, but it still seems to be a wasteland.
Libraries like
- GitHub - mike-matera/ArduinoSTL: An STL and iostream implementation based on uClibc++ that supports my CS-11M class.
- GitHub - muwerk/ustd: Micro-standard-library providing minimal and portable array, queue and map for attiny avr, arduinos, esp8266/32 and linux, mac
suplement the gap here with their own implementations. Though ArduinoSTL seems to also have lacking modern functional support. Using ustd:
[env:megaatmega2560]
platform = atmelavr
board = megaatmega2560
framework = arduino
; build flags needed by library for identifaction and correct compiling
build_flags= -D __ATMEGA__ -Wno-reorder
; correctly search chained libraries
lib_ldf_mode = chain+
lib_deps =
ustd
#include <Arduino.h>
#include "platform.h"
//subfunctionality
#include "array.h"
#include "queue.h"
#include "map.h"
#include "functional.h"
//instead of std::function, use ustd::function
//uncomment this to be able to just use "function" as typename
//using ustd::function;
void print_num(int i)
{
Serial.println(i);
}
void setup() {
Serial.begin(115200);
//create function from function pointer
ustd::function<void(int)> f_display = print_num;
f_display(-9);
}
void loop() {
}
that code compiles.
Though it can be of course argued what good it is to use the C++ STL on these constrained devices…