簡體   English   中英

如何在C中串聯兩個字符串宏?

[英]How do I concatenate two string macros in C?

我正在嘗試為我的程序實現VERSION宏,在某些情況下需要更改該宏。

宏VERSION是通過Makefile定義的(git info放在此處),它是一個字符串。 現在,我有一組#define開關,並且我希望VERSION反映其中的哪個開關。 現在看起來如下(main.h):

#define COMPLEX_DEPOSITION // This is switch. later in code it is used in #ifdef...#endif construction.

#ifdef COMPLEX_DEPOSITION
#define CD "_COMP_DEP" // this is the string I want to put in the end of VERSION
#define VERSION_ VERSION CD

#undef VERSION // this is to suppress 'macro redefinition' warning
#define VERSION VERSION_
#undef VERSION_
#endif

好吧,我遇到了很多錯誤,其中大多數使我認為C預處理器可以按隨機順序處理文件中的行:

后來我有一個更復雜的東西,旨在使VERSION -> VERSION_WLT_GAP_2

#define WIRESLIFETIMES

#ifdef WIRESLIFETIMES
#define GAP 2
#define VERSION_ (VERSION ## "_WLT_GAP_" ## #GAP)
#define VERSION VERSION_
#undef VERSION_
#endif

我不知道該怎么辦,如果可能的話

字符串文字彼此相鄰時自然連接

"foo" "bar""foobar"相同。

對於第二個示例,您可能需要:

#define CAT_(A,B) A##B
#define CAT(A,B) CAT_(A,B)

#define GAP 2
#define VERSION CAT(VERSION_WLT_GAP_ , GAP)

VERSION //expands to VERSION_WLT_GAP_2

我建議稍微嘗試一下gcc -E / clang -E ,以了解宏的工作原理,然后再嘗試使用它們編寫任何復雜的東西。

好吧,答案似乎如下:

// https://stackoverflow.com/questions/5256313/c-c-macro-string-concatenation
// Concatenate preprocessor tokens A and B without expanding macro definitions (however, if invoked from a macro, macro arguments are expanded).
#define PPCAT_NX(A, B) A ## B

// Concatenate preprocessor tokens A and B after macro-expanding them.
#define PPCAT(A, B) PPCAT_NX(A, B)

// Turn A into a string literal without expanding macro definitions (however, if invoked from a macro, macro arguments are expanded).
#define STRINGIZE_NX(A) #A

// Turn A into a string literal after macro-expanding it.
#define STR(A) STRINGIZE_NX(A)


#define COMPLEX_DEPOSITION

#ifdef COMPLEX_DEPOSITION
#define CD "_COMPDEP"
#else
#define CD ""
#endif


#define WIRESLIFETIMES

#ifdef WIRESLIFETIMES
#define GAP 2
#define WLT STR(PPCAT(_WLT:G, GAP))
#define DISABLE_METROPOLIS
#else
#define WLT ""
#endif

#define VERSION VERSIONX CD WLT

產生V008.1-11-g68a9c89cb4-dirty_COMPDEP_WLT:G2 ,我對此很滿意。

必須指出的是,我改變-DVERSION=...-DVERSIONX=...里面的Makefile

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM