C macro for inlining functions with IAR compiler

378 views Asked by At

With previous gcc compiler we did this:

#define DO_PRAGMA(x)        _Pragma(#x)
#define PACK_ON(n)          DO_PRAGMA(pack(n))

so in effect would mean PACK_ON(2) would expand to be _Pragma(pack(2)) Then we would use it like this

PACK_ON(2)
typedef struct{
...
};

However, the IAR compiler wants something like this: _Pragma("pack(2)") So I've tried to implement the macro for pack in these following non compiling ways:

#define DO_PRAGMA(x)        _Pragma(#x)
#define PACK_ON(n)          DO_PRAGMA(" ## "pack(#n)"" ## ")
#define PACK_ON(n)          DO_PRAGMA(" ## pack(#n) ## ")
#define PACK_ON(n)          DO_PRAGMA(" ## #pack(n) ## ")
#define PACK_ON(n)          DO_PRAGMA(" ## #pack(n) ## ")
#define PACK_ON(n)          DO_PRAGMA("pack(n)")
#define PACK_ON(n)          DO_PRAGMA("pack(#n)")
#define PACK_ON(n)          DO_PRAGMA(pack(#n))
#define PACK_ON(n)          DO_PRAGMA(pack(n))
#define PACK_ON(n)          DO_PRAGMA(#pack(#n))
#define PACK_ON(n)              \#if (n == 1)\ _Pragma("pack(1)")
#define PACK_ON(n)          _Pragma("pack( ## #n ## )")
#define PACK_ON(n)          _Pragma("pack( ## n ## )")
#define PACK_ON(n)          _Pragma("pack(n)")
#define PACK_ON(n)          _Pragma("pack(#n)")

Does anyone have a macro that would work with IAR compiler for packing of various sizes of n ? If not I'll just force everything to pack size 1 and manually change the structures that use 2 and 4.

Temporary Solution: I've managed to get around this by doing this:

#define PACK_ON(n)              _Pragma("pack(1)")

and manually changing the small handful that were PACK_ON(2) and PACK_ON(4)

2

There are 2 answers

5
Lundin On

Given that the compiler supports pack(1), push and pop pragmas, then this standard C solution works:

#include <stdio.h>

#define DO_PRAGMA(x)        _Pragma(#x)
#define PACK_ON(n)          _Pragma("pack(push)") DO_PRAGMA(pack(n))
#define PACK_OFF            _Pragma("pack(pop)")

PACK_ON(1)
typedef struct 
{
  char c;
  short s;
} foo;
PACK_OFF

typedef struct 
{
  char c;
  short s;
} bar;


int main()
{ 
  printf("%zu\n", sizeof(foo));
  printf("%zu\n", sizeof(bar));
}

Output

3
4

Tested on gcc, clang and icc with strict standard settings (-std=c11 -pedantic-errors).

0
Adeishere On

with the above PACK_ON I get error identifier "pack" is undefined. I've managed to get around this by doing this: #define PACK_ON(n) _Pragma("pack(1)") and manually changing the small handful that were PACK_ON(2) and PACK_ON(4)