[英]C macro for inlining functions with IAR compiler
使用以前的 gcc 編譯器,我們這樣做了:
#define DO_PRAGMA(x) _Pragma(#x)
#define PACK_ON(n) DO_PRAGMA(pack(n))
所以實際上意味着 PACK_ON(2) 將擴展為 _Pragma(pack(2)) 然后我們會像這樣使用它
PACK_ON(2)
typedef struct{
...
};
但是,IAR 編譯器想要這樣的東西: _Pragma("pack(2)") 所以我嘗試通過以下非編譯方式來實現 pack 的宏:
#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)")
有沒有人有一個宏可以與 IAR 編譯器一起使用來打包各種大小的 n? 如果不是,我將強制所有內容打包大小 1 並手動更改使用 2 和 4 的結構。
臨時解決方案:我已經設法通過這樣做來解決這個問題:
#define PACK_ON(n) _Pragma("pack(1)")
並手動更改 PACK_ON(2) 和 PACK_ON(4) 的一小部分
鑒於編譯器支持pack(1)
、 push
和pop
pragma,那么這個標准的 C 解決方案可以工作:
#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
使用嚴格的標准設置 ( -std=c11 -pedantic-errors
) 在 gcc、clang 和 icc 上進行測試。
使用上面的 PACK_ON 我得到錯誤標識符“pack”未定義。 我已經設法通過這樣做來解決這個問題:#define PACK_ON(n) _Pragma("pack(1)") 並手動更改少數 PACK_ON(2) 和 PACK_ON(4)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.