Home > Blockchain >  Define and use a string constant in C
Define and use a string constant in C

Time:12-12

I have code that uses multiple different strings in the code, like "my-app/123" and "my-app/#". Sometimes it's also used for further formatting (include other variables with % placeholders). Now I need to make this prefix more configurable by adding a #define statement for the string prefix. It then looks like this:

#define MQTT_TOPIC "my-app"

But how can I use it without writing several lines of code and allocating memory for every usage? I've tried this but the compiler doesn't understand what I want:

esp_mqtt_client_subscribe(client, MQTT_TOPIC   "/#", 0)

Strings are so complicated in C. The compiler should be able to resolve all of this because it's a preprocessor symbol, not a runtime string.

CodePudding user response:

Change MQTT_TOPIC "/#" to MQTT_TOPIC "/#". During compilation, adjacent string literals are concatenated.

  • Related