第一阶段——代码中定义并使用
//test.c
#include <stdio.h>
#include <stdlib.h>
#define NEED_PRINTF 1
int main ()
{
#ifdef NEED_PRINTF
printf("NEED_PRINTF = %d\n",NEED_PRINTF);
#endif
printf("test\n");
return 0;
}
代码中定义了一个宏“NEED_PRINTF”,根据需要修改代码
第二阶段——将宏写到MakeFile中
//test.c
#include <stdio.h>
#include <stdlib.h>
int main ()
{
#ifdef NEED_PRINTF
printf("NEED_PRINTF = %d\n",NEED_PRINTF);
#endif
printf("test\n");
return 0;
}
//Makefile
CFLAGS=-g -Wall -DNEED_PRINTF=2
test: test.o
gcc -o test test.o
test.o: test.c
gcc -c ${CFLAGS} test.c
clean:
rm *.o
rm test
第三阶段——将宏在make时输入
test.c不变,只修改Makefile
CFLAGS=$(NEED_PRINTF)
CFLAGS+=-g -Wall
test: test.o
gcc -o test test.o
test.o: test.c
gcc -c ${CFLAGS} test.c
clean:
rm *.o
rm test
在编译时输入"make NEED_PRINTF=-DNEED_PRINTF=3"
运行代码会打印NEED_PRINTF = 3
第四阶段——运行脚本传参
test.c、Makefile不变
添加build.sh
#!/bin/bash
make clean
make NEED_PRINTF=-DNEED_PRINTF=$1
终端运行:sh +x build.sh 4
运行代码会打印NEED_PRINTF = 4