Search code examples
cconcatenation

How can I concatenate a string and a variable which is types of int?


I have to write a macro which concatenate a variable that hold a number with GPIO. For example:

 #define SELECT_PIN(pin) GPIO##pin

int main (void)
{
  uint16_t x=5;
  ioregister.SELECT_PIN(x)= OUTPUT;
}

This macro naturally output the result like "this structure has no element like GPIOx" .

I need your helps guys.


Solution

  • How can I concatenate a string and a variable which is types of int?

    You cannot. You may convert an int to a string and concatenate - using snprintf.

    I have to write a macro which concatenate a variable that hold a number with GPIO

    That is not possible - macro has to execute at compile time in preprocessor - it can't depend on a value of a variable.


    You can write a function.

    void pin_set(register_type reg, uint16_t idx, bool value) {
         if (idx == 0) {
             reg.GPIO0 = val;
         } else .... etc. ..
    }
    
    bool pin_get(register_type reg, uint16_t idx) {
        ... similar to above ...
    }
    
    int main() {
      uint16_t x=5;
      pin_set(ioregister, x, OUTPUT);
    }
    

    Typically GPIOX are some convenience struct members defined inside an union and such set and get functions use bit masks to do the operation on the other struct member that allows to access whole register as one word.