繁体   English   中英

C编程:使用宏调用函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM