[英]CPP: Escaping macro identifiers
有沒有一種方法可以在AC預處理器(cpp)中轉義宏名稱(標識符)?
我想使用可讀的宏名稱對某些Web代碼(html,css ...)進行條件化。
條件css文件的示例:
/*root*/
some rootcode
#if height==480
/* height 480 */
.page {
line-height:23px;
}
#elif height<480
/* height < 480 */
.page {
line-height:46px;
}
#endif
的調用
cpp -P -D height=480 -oout.css css.ccss
結果(刪除換行符后)
some rootcode
.page {
line-480:23px;
}
但是“第480行 ”是錯誤的。
有沒有一種方法可以在代碼中轉義“高度”而不更改宏名稱或對其進行字符串化?
您可以:
1)取消定義宏:
#undef height
2)使用類似標准的大寫字母重命名宏:
#define HEIGHT
3)在處理文件之前使用防護措施:
#if height==480
#define HEIGHT_480
#undef height
#endif
#if height>480
#define HEIGHT_OVER_480
#undef height
#endif
/*root*/
some rootcode
#if HEIGHT_480
/* height 480 */
.page {
line-height:23px;
}
#elif HEIGHT_OVER_480
/* height < 480 */
.page {
line-height:46px;
}
#endif
未定義后,第一個丟失信息。 如果宏的廣泛使用,第二個是不切實際的。
第三個是IMO的最佳選擇。 我已經看到它在生產代碼中使用過,在這些代碼中,這樣的東西是必需的。
我使用Luchian Grigore的想法來取消定義使用的文件名,並且發現了這個問題的(幾乎)通用解決方案:
在條件語句的開頭包括“ define.file”,在給定條件之后包括“ undefine.file”。
因此,問題被簡化為兩個必須保留的宏名稱:DEFINEFILE和UNDEFINEFILE。 但是可以使用其哈希碼或隨機名稱對這兩個宏進行加密,以避免在條件文本中使用此名稱。
“ define.file”:
#define height 480
#define os 1
“ undefine.file”
#undef height
#undef os
“ conditionalcss.ccss”
/*root*/
some rootcode
#include __DEFINEFILENAMEPATH__
#if height==480
#include __UNDEFINEFILENAMEPATH__
/* height 480 */
.page {
line-height:23px;
}
#include __DEFINEFILENAMEPATH__
#elif height<480
#include __UNDEFINEFILENAMEPATH__
/* height > 480 */
.page {
line-height:46px;
}
#include __DEFINEFILENAMEPATH__
#endif
#if os==1
#include __UNDEFINEFILENAMEPATH__
os is windows (if 1 refers to windows)
and height also undefined i hope
#endif
最后,使用參數定義和未定義文件的cppcall:
cpp -P -D __DEFINEFILENAMEPATH__="\"define.file\"" -D __UNDEFINEFILENAMEPATH__="\"undefine.file\"" -oout.css css.ccss
有了這個想法,重新格式化的“ out.css”看起來像:
some rootcode
.page {
line-height:23px;
}
os is windows (if 1 refers to windows)
and height also undefined i hope
該解決方案僅具有兩個宏的缺點,並且由於多次導入而可能導致性能不佳。
我希望它可以幫助其他人解決他們的問題。
格蕾茲·阿夢卡
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.