enomis
enomis

Reputation: 27

How to create a macro in c++ with inside a String variable?

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

Upvotes: 0

Views: 147

Answers (2)

jdenozi
jdenozi

Reputation: 222

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;
}

Upvotes: 1

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123566

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.

Upvotes: 5

Related Questions