[英]C programming: Calling a function with macros
我想從涉及宏的函數中調用另一個函數。
這是一個示例:
#if RAND
int functionA() {
//How to call the bottom function from here?
}
#else
int functionA() {
}
注意它們都是相同的函數名。 如何從“ if”函數調用“ else”函數。
謝謝
那是沒有道理的,也是不可能的。 宏由預處理器處理 ,因此編譯器甚至根本看不到禁用功能的代碼!
如果可以,請避免使用宏。 他們欺騙了您,使您無法獲得聰明的編譯器的好處。 盡可能多地用C編寫代碼,而不要用搜索和替換的技巧。
例如,您可以創建一個函數int functionA(int type)
並在type
有條件地實現不同的部分。
你不能。 取決於RAND
的值,編譯器將僅創建函數之一。
我看不到如何直接完成。 而是在#if/#else
外部創建一個單獨的函數,例如functionB()
,然后將所有代碼從最后一個functionA()
移到那里,並用對functionB()
的調用來替換。 然后,你可以調用functionB()
從第一個functionA()
您將近距離獲得以下內容之一:
int functionA()
{
#if RAND
/* stuff that happens only when RAND is defined */
#endif
/* stuff that happens whether RAND is defined or not */
}
也許這樣:
#if RAND
#define FUNCA() functionA_priv()
#else
#define FUNCA() functionA()
#endif
int FUNCA()
{
/* the non-RAND version of functionA().
* It's called functionA_priv() when RAND is defined, or
* functionA() if it isn't */
}
#if RAND
int functionA()
{
/* The RAND version of functionA(). Only defined if RAND
* is defined, and calls the other version of functionA()
* using the name functionA_priv() via the FUNCA() macro */
FUNCA();
}
#endif
使用的FUNCA()
中的第二個版本宏允許的正常版本functionA()
遞歸調用自身使用FUNCA()
宏而不是functionA()
如果必要的話,由於FUNCA()
將提供合適的標識符無論哪個名稱用於功能。
你不知道 編譯程序時會評估預處理器宏。 在這種情況下,將僅根據編譯時RAND
的值來編譯其中一個功能。 似乎您可能要在此處使用if語句,而不是預處理器宏。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.