Matt
Matt

Reputation: 179

C Code Preprocessor

I have a piece of code as below

    Local_DATA[0] =  * ((int32_T *) event_structure + 1);
    Local_DATA[1] =  * ((int32_T *) event_structure + 2);
    Local_DATA[2] =  * ((int32_T *) event_structure + 3);
    Local_DATA[3] =  * ((int32_T *) event_structure + 4);

I would have to make a preprocessor like

    #ifdef ABC
            Local_DATA[0] =  * ((int32_T *) event_structure + 1);
            Local_DATA[1] =  * ((int32_T *) event_structure + 2);
            Local_DATA[2] =  * ((int32_T *) event_structure + 3);
            Local_DATA[3] =  * ((int32_T *) event_structure + 4);
    #else
            Local_DATA[0] =  ntohl (* ((int32_T *) event_structure + 1));
            Local_DATA[1] =  ntohl (* ((int32_T *) event_structure + 2));
            Local_DATA[2] =  ntohl (* ((int32_T *) event_structure + 3));
            Local_DATA[3] =  ntohl (* ((int32_T *) event_structure + 4));
    #endif

I have many lines of code where I have to manually perform this. Is there any way to have something like a macro defined?

Upvotes: 0

Views: 132

Answers (4)

BLUEPIXY
BLUEPIXY

Reputation: 40155

#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/arithmetic/add.hpp>

#ifdef ABC
  #define PROC1(z, n, func) Local_DATA[n] =  * ((int32_T *) event_structure + BOOST_PP_ADD(n, 1));
#else
  #define PROC1(z, n, func) Local_DATA[n] =  func (* ((int32_T *) event_structure + BOOST_PP_ADD(n, 1)));
#endif
#define PROC(func, n) BOOST_PP_REPEAT(n, PROC1, func)

...

PROC(ntohl, 4);

Upvotes: 0

Steve Barnes
Steve Barnes

Reputation: 28405

#ifdef ABC
   #define REF_PTR(s, off) (* ((int32_T *) s + off))
#else
   #define REF_PTR(s, off) (ntohl (* ((int32_T *) s + off)))
#endif

Local_DATA[0] = REF_PTR(event_structure, 1);
// etc

Should do the trick.

Upvotes: 2

Ed Heal
Ed Heal

Reputation: 60027

You only need to do this:

   Local_DATA[0] =  ntohl (* ((int32_T *) event_structure + 1));
   Local_DATA[1] =  ntohl (* ((int32_T *) event_structure + 2));
   Local_DATA[2] =  ntohl (* ((int32_T *) event_structure + 3));
   Local_DATA[3] =  ntohl (* ((int32_T *) event_structure + 4));

As if the network order is the same as the host order ntohl will be a macro which is a noop. Otherwise the ntohl will do the necessary operation

Upvotes: 2

Adam Rosenfield
Adam Rosenfield

Reputation: 400602

Sure, just use a function-style macro:

#if ABC
#define MYORDER(x) (x)
#else
#define MYORDER(x) ntohl(x)
#endif
...

Local_DATA[0] =  MYORDER(* ((int32_T *) event_structure + 1));
Local_DATA[1] =  MYORDER(* ((int32_T *) event_structure + 2));
Local_DATA[2] =  MYORDER(* ((int32_T *) event_structure + 3));
Local_DATA[3] =  MYORDER(* ((int32_T *) event_structure + 4));

Upvotes: 1

Related Questions