一个实用的编译技术
使用编译参数结合宏定义实现了在编译时指定不同的输出等级(makefile
+ c
)
// defs.h
#include <stdio.h>
// Output level: ERROR(31) > WARN(93) > INFO(34) > DEBUG(32) > TRACE(90)
// `fmt` can only be face-value
#ifdef TRACE_OUTPUT
#define trace(fmt, arg...) \
printf("\x1b[90m" fmt "\x1b[0m", ##arg)
#define TRACE_ENABLE
#else
#define trace(fmt, arg...)
#endif
#if (defined TRACE_ENABLE) || (defined DEBUG_OUTPUT)
#define debug(fmt, arg...) \
printf("\x1b[32m" fmt "\x1b[0m", ##arg)
#define DEBUG_ENABLE
#else
#define debug(fmt, arg...)
#endif
#if (defined DEBUG_ENABLE) || (defined INFO_OUTPUT)
#define info(fmt, arg...) \
printf("\x1b[34m" fmt "\x1b[0m", ##arg)
#define INFO_ENABLE
#else
#define info(fmt, arg...)
#endif
#if (defined INFO_ENABLE) || (defined WARN_OUTPUT)
#define warn(fmt, arg...) \
printf("\x1b[93m" fmt "\x1b[0m", ##arg)
#define WARN_ENABLE
#else
#define warn(fmt, arg...)
#endif
#if (defined WARN_ENABLE) || (defined ERROR_OUTPUT)
#define error(fmt, arg...) \
printf("\x1b[31m" fmt "\x1b[0m", ##arg)
#define ERROR_ENABLE
#else
#define error(fmt, arg...)
#endif
// main.c
#include "defs.h"
int main() {
error("This is an error.\n");
warn("This is a warn.\n");
info("This is an info.\n");
debug("This is an debug.\n");
trace("This is a trace.\n");
return 0;
}
# makefile
SRCS = $(wildcard *.c)
OBJS = $(addsuffix .o, $(basename $(SRCS)))
CC = gcc
CXX = g++
LOG = WARN
CCFLAGS =
main: $(OBJS)
$(CC) $(CCFLAGS) -D $(LOG)_OUTPUT $(OBJS) -o main
clean:
rm $(OBJS) *.exe
当使用编译命令
$ make main LOG=INFO
的时候,只有 error
、warn
和 info
方法会输出到屏幕,而 debug
和 trace
方法不会。