main.c
#include <stdio.h>
#include "log.h"
extern void lib_fun();
int main()
{
DEBUG_LOG("ni hao\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 <stdio.h>
#ifdef LOG_ID
#define STR1(R) "[" #R "]"
#define STR2(R) STR1(R)
#define STR3 STR2(LOG_ID)
#else
#define STR3
#endif
#define DEBUG_LOG(pmt,...) printf(STR3 pmt,##__VA_ARGS__)
#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 $^