c - C 中宏中的宏

标签 c function macros

请帮我解决这个问题。这是在 C 中获取行号、文件名和 var args 的示例代码。当我尝试运行它时,出现了一些错误。我相信有很多方法可以做到这一点。但是我必须使用现有的代码来实现一些功能。任何帮助或建议将不胜感激。

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#define MY_MACRO1(fmt, args...)                \
 {                                             \
   char buf_d[1024];                       \
   MY_MACRO2(__FILE__, __LINE__,call_func(buf_d,sizeof(buf_d),fmt,##args));   \
 }   

#define MY_MACRO2(__FILE__, __LINE__,fmt, ...)  printf("%s : %d -> %s : \n",__FILE__, __LINE__, __VA_ARGS__);

char * call_func(char *buf_t, size_t size, const char *fmt, ...)
{
  va_list ap;
  va_start(ap,fmt);
  vsnprintf(buf_t, size, fmt, ap);
  va_end(ap);
  return buf_t;
}


int main()
{
  printf("\n Now I am printintg macro....\n");
  MY_MACRO1("Macro is working fine..\n");
  return 0;
}

输出:

请查找宏扩展。宏中的最后一个参数(函数返回值)丢失。

char buf_d[1024];
printf("%s : %d -> %s : \n","file.c",35, );;

错误:

file.c:35:83: error: expected expression
{ char buf_d[1024]; printf("%s : %d -> %s : \n","file.c", 35, );; };
                                                              ^

产生了 1 个错误。

最佳答案

好乱啊!让我们清理一下:

代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>


#define DEBUG_MSG( _msg, ... )  do {print_debug_msg( __FILE__, __LINE__, __FUNCTION__, _msg, ## __VA_ARGS__ ); }while(0)


void print_debug_msg( const char * module, int line, const char * func, const char * fmt, ... )
{
    va_list va;
    char buf[ 1024 ] = {0};

    va_start( va, fmt );
    vsnprintf( buf, sizeof(buf), fmt, va );
    va_end( va );

    printf( "%s:%d - %s() - %s\n", module, line, func, buf );
}


int myfunc( const char * msg )
{
    DEBUG_MSG( "Message: %s",  msg );

    return 0;
}


int main( int argc, char * argv[] )
{
    DEBUG_MSG("The quick brown fox jumps over the lazy dog.");

    DEBUG_MSG("Pack my box with five dozen liquor jugs.");

    myfunc( "How vexingly quick daft zebras jump" );

    myfunc("The five boxing wizards jump quickly.");

    return 0;
}

/* eof */

编译:

$ gcc -Wall macro.c -o macro

测试:

$ ./macro 
macro.c:32 - main() - The quick brown fox jumps over the lazy dog.
macro.c:34 - main() - Pack my box with five dozen liquor jugs.
macro.c:24 - myfunc() - Message: How vexingly quick daft zebras jump
macro.c:24 - myfunc() - Message: The five boxing wizards jump quickly.

引用资料:

1) Recommended C Style and Coding Standards (Macros)

2) GCC Manual - Standard Predefined Macros

希望对您有所帮助!

关于c - C 中宏中的宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37145693/

相关文章:

java - 线程 "main"java.lang.UnsatisfiedLinkError 3 中的异常

javascript - 如何在保持相同 API 的同时将此 JavaScript 包装在立即调用的函数表达式 (IIFE) 中?

python - 如何将列表与 python 中的另一个列表进行匹配

macros - common lisp 中的程序集生成宏

c - 如何在 C 中打开 4 个字符的字符串?

generics - 在 Rust 中使用宏创建 impl-block 的问题

c - C 宏中括号的必要性

c - 您将如何确定堆栈在系统中增长还是下降?

c++ - 为什么这不是 C/C++ 中的无限循环

python - 将列表理解表达式拆分为多行以更好地了解发生了什么?