Solved Problem with pre-processor directives for multiple architectures

Greetings,

i am trying to make a piece if code compile on both ESP8266 and ESP32.

there are differences in library names and parameters, which i solve like this

#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#elif defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#include <WebServer.h>
#include <SPIFFS.h>
#endif


#if defined(ARDUINO_ARCH_ESP8266)
  #define FILE_MODE_R "r"
  #define FILE_MODE_W "w"
  typedef ESP8266WebServer  WiFiWebServer;
#elif defined(ARDUINO_ARCH_ESP32)
  #define FILE_MODE_R FILE_READ
  #define FILE_MODE_W FILE_WRITE
  typedef WebServer WiFiWebServer;
#endif

the problem is that some WiFi server class methods have a different name
Example is setting the host name
ESP8266 -> WiFi.hostname();
ESP32 -> WiFi.setHostname();

i tried #define Wifi.hostname WiFi.setHostname to replace the method name in the #elif defined(ARDUINO_ARCH_ESP32) section above, but that throws an error, i assume the point (.) is an illegal character in macros.

The code contains

  WiFi.hostname(_hostname);
  WiFi.begin(ssid, password);

this evetually results in the error: error: 'class WiFiClass' has no member named 'hostname'.

I know i can litter my code with #if defined(ARDUINO_ARCH_ESP8266) statements, but it would be so much easier to do this once.

If anyone has a suggestion for me, i would be grateful.

thanks for your time.

Rob.

You can do this:

#elif defined(ARDUINO_ARCH_ESP32)
#define hostname setHostname

I would probably prefer the

#if defined(ARDUINO_ARCH_ESP8266)
WiFi.hostname(host);
#elif defined(ARDUINO_ARCH_ESP32)
WiFi.setHostname(host);
#endif

approach because I try to use #define as little as possible, but the choice is yours.

Use in the code

WiFi.SETHOSTNAME(_hostname);

and define SETHOSTNAME in the 8266 part:

#define SETHOSTNAME hostname

and in ESP32:

#define SETHOSTNAME setHostname

@pert, @pylon,

thanks a million for your suggestions.
i will try pert's

#elif defined(ARDUINO_ARCH_ESP32)
#define hostname setHostname

first, as that was what i tried to achieve.
Pylons alternative makes a good second choice.

thanks again,

Rob

I actually like pylon's more but I would use SET_HOSTNAME because ALL_CAPS_WITH_UNDERSCORES is a common style convention for macros. This makes it easy to tell what's a macro and can prevent some confusion. The use of macros can make your code really hard to troubleshoot.