C语言使用宏来指定打印信息头部

main.c

#include 
#include "log.h"

extern void lib_fun();
int main()
{
	DEBUG_LOG("ni hao\r\n");
	DEBUG_ERR("hehe\r\n");	
	lib_fun();
	return 0;
}

lib.c

#define LOG_ID lib //如果不是在编译时传入LOG_ID需要在导入log.h前去定义它
#include "log.h"

void lib_fun()
{
	DEBUG_LOG("lib fun\r\n");
}

log.h

#ifndef _LOG_H_
#define _LOG_H_

#include 

#ifdef LOG_ID
#define STR1(R) "[" #R "]"
#define STR2(R) STR1(R)
#define STR3    STR2(LOG_ID)

#define STR11(R) "[ERROR-" #R "]"
#define STR12(R) STR11(R)
#define STR13    STR12(LOG_ID)
#else
#define STR3
#define STR13
#endif


#define DEBUG_LOG(pmt,...) \
    do \
    {   \
        printf(STR3 pmt,##__VA_ARGS__); \
    }while(0)

#define DEBUG_ERR(pmt,...) \
    do \
    { \
        printf(STR13 "%s:%s:%d" pmt,__FILE__,__FUNCTION__,__LINE__,##__VA_ARGS__);\
    }while(0)

#endif

Makefile

all:main.o lib.o
     gcc $^ -o main

 main.o:main.c
     gcc -DLOG_ID=main -c $^

 lib.o:lib.c
     gcc  -c $^
   
.PHONY:
clean:
        rm -rf *.o main

![![在这里插入图片描述](https://img-blog.csdnimg.cn/20200522141053228.pn](https://img-blog.csdnimg.cn/2020061619460167.png

你可能感兴趣的:(C/C++,学习)