Home > Software engineering >  How to create a macro in c with inside a String variable?
How to create a macro in c with inside a String variable?

Time:12-16

I have in the past defined in the macro in the following way..

#define MACRO_NAME "devices/987654/bucket"

I would like to replace the number with a String variable class String in c .

How can I define a new macro with inside with string ?

Thanks

CodePudding user response:

You cannot. Make it a String (I suppose this is arduino, otherwise you'd be using std::string):

const String string_name = String("devices/")   the_number   String("/bucket");

Macros are expanded by the preprocessor as the first step of compilation. At that stage there are no variables or strings, only token.

CodePudding user response:

You can do whatever you want by using a macro function. Here is a small example using std::string

#include <iostream>
#include <string>

#define MACRO_NAME(NUMBER, OUT){replaceNumber(NUMBER, OUT);}        

void replaceNumber(int32_t number, std::string &out){
    const std::string devices = "devices/";
    const std::string bucket = "/bucket";
    out = devices   std::to_string(number)   bucket;
}

int main()
{
    std::string name; 
    MACRO_NAME(213, name);
    std::cout << name << std::endl;
    return 0;
}
  •  Tags:  
  • c
  • Related