[英]How to identify whether a variable exists inside a C function for logging?
如何檢查某個函數中是否存在變量? 目標是定義一個日志函數,該函數將打印消息以及一些可能存在或不存在的變量。
我一直在嘗試使用宏來實現這一點,但無濟於事:(
// if bar exists, print bar_id and the log.
#if EXIST(bar)
#define Log LogWithBar
#endif
void LogWithBar()
{
// print as with Log and add bar.data value
}
void func1(foo bar, ...)
{
bar.data = 111
...
Log("First")
// First 111
}
void func2( ...) // no bar
{
...
Log("First")
// First
}
詳細的用例是我有一個包含數百個函數的大型代碼,其中許多具有一些通用結構,但許多其他沒有。 我想讓日志記錄函數在它存在時從這個結構中打印一些值(連同實際的日志字符串),如果它不存在則只打印日志字符串。
#include <stdio.h>
// Define a "bar" with external scope with a type we can distinguish.
const struct DummyType { char dummy; } bar;
/* If "bar" has the dummy type, there is no local "bar" hiding it, so do
nothing. Otherwise, there is a local "bar" hiding the external one, so
do something.
*/
#define Log(x) \
_Generic(bar, \
struct DummyType: (void) 0, \
default: puts(x) \
)
// This function has no "bar", so nothing will be logged.
void func0(void)
{
Log("func0");
}
// This function has a "bar", so its message will be logged.
void func1(int bar)
{
Log("func1");
}
int main(void)
{
func0();
func1(0);
}
在引入_Generic
之前的 C 版本中,您可以測試地址:
// Define a "bar" with external scope to serve as a sentinel.
const char bar;
const void *pbar = &bar;
/* If the address of bar is pbar, there is no local "bar" hiding it, so do
nothing. Otherwise, there is a local "bar" hiding the external one, so
do something.
*/
#define Log(x) \
do if ((const void *) &bar != pbar) puts(x); while (0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.