Preprocessor use number to build NAME an IP

Hello!

Let's say I have 3 ESP32 each as a client (CL) with same programm, sending data to a server.
I'm looking for the best way to define just one number to build the CLname and the CLip-address to minimize the editing .

#define CL_NUMBER 3
#define CL_NUMBER_str "3"
#define CL_NAME "CL" CL_NUMBER_str
#define CL_IP4 50+CL_NUMBER

IPAddress cl_IP(10, 0, 0, CL_IP4);
IPAddress gateway(10, 0, 0, 138);
IPAddress dns(10, 0, 0, 138); //primaryDNS
IPAddress subnet(255, 255, 255, 0);

loop(){
		// something else
			strcpy(udp_send_char_message,CL_NAME);
			strcat(udp_send_char_message,"/sensors/MAX_exceeded");
		// something else
}

is working. But I have to edit 2 lines. Is there a way to reduce it to just 1 line to define CL_number and using it in CL_NAME and CL_IP.
The above code is just a part of an example, but I hope you see what I mean.

Thank you!

You can "stringizing "the macro argument by "#":

#define CL_NUMBER 3
#define CL_NAME(s) CL_S(s)
#define CL_S(CL)  "CL"#CL
#define CL_IP4 (50+CL_NUMBER)

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
Serial.println(CL_NAME(CL_NUMBER));
}

See details there:

3 Likes

Whow, it worked!

I've seen this solution before, but didn't know how to use it exactly and made a fault - so it didn't work.
But your detailed example made my day!
Thank you!

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.