There is, as you may expect with C, many different ways of doing this.
The simplest is probably to use, instead of a const variable, a preprocessor macro.
In C you can concatenate string literals like this:
print("AT+BIND=" "abcd,ef,ghijkl");
Note the lack of anything but spaces between the strings - they are concatenated together. You can even do it on separate lines - it's a technique that is great for incredibly long strings.
Now you can, of course, replace one of those with a preprocessor macro:
#define BT_ADDRESS "abcd,ef,ghijkl"
print("AT+BIND=" BT_ADDRESS);
print("AT+LINK=" BT_ADDRESS);
The preprocessing replaces BT_ADDRESS with the string literal "abcd,ef,ghijkl" and all is well.
Other options, depending on what print
does, is to expand it to take two const char *
parameters and deal with them both separately. For instance, you might have:
void print(const char *command, const char *data) {
Serial.print(command);
Serial.println(data);
}
print("AT+BIND=", BT_ADDRESS);
If you don't know how many parameters you may want to pass you could use variadic arguments:
#include <stdarg.h>
void print(int count, ...) {
va_list args;
va_start args, count);
for (int i = 0; i < count; i++) {
const char *arg = va_arg(args, const char *);
Serial.print(arg);
}
va_end(args);
}
print(2, "AT+BIND=", BT_ADDRESS);
Yet another option is to pre-format the data into a single string using the various string operators. For example:
int len = strlen("AT+BIND=") + strlen(BT_ADDRESS);
char temp[len + 1]; // Be sure to keep space for the terminating NULL.
strcpy(temp, "AT+BIND=");
strcat(BT_ADDRESS);
print(temp);
I could go on all night with different options... The first one using the preprocessor is probably easiest though.
print
does.