Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Define and use a string constant in C

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading