#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
//Code in here will only be compiled if an Arduino Mega is used.
Is it possible to do the same for other types of microcontrollers? For example the one in ESP8266? What should I look for?
The mentioned macros are built-in macros provided by avr-gcc. They are used to determine for which device to compile, for example by avr-libc. Actually, these macros are no more built-in in the compiler / preprocessor today but provided by the device-specs file device-specs/specs-<device>
that injects respective -D__AVR_<DEVICE>__
to the preprocessor's command line according to -mmcu=<device>
.
What you can use for AVR is
#ifdef __AVR__
when compiling for AVR and, which is still a built-in macro from avr-gcc / avr-g++.
ESP8266 is a completely different architecture; you would use xtensa-g++ to compile code for that µC and that incarnation of GCC built-in defines __xtensa__
and __XTENSA__
(and definitely not __AVR__
).
However, whereas device support in the AVR tools is very sophisticated and hundreds of different -mmcu=<device>
options are recognized by avr-gcc, this is not the case for xtensa. You will have to define your own macros if you want to distinguish for different xtensa derivatives.
As avr and xtensa are very different architectures, you can also put the architecture specific stuff in own modules, like eeprom-avr.cpp
that provides read_from_eeprom
or whatever for avr and is only included in the build when building for avr with avr-g++, and a similar xtensa-only module eeprom-xtensa.cpp
that's only included when built with xtensa-g++.
How to programmarically identify if the code is being compiled for AVR or ESP8266?
#if defined (__AVR__)
/* Code for AVR. */
#elif defined (__XTENSA__)
/* Code for ESP8266. */
#else
#error Compiling for unsupported target.
#endif