一、介绍
本文用实例介绍Makefile的一些使用规则和用法
二、一些用法
1. 宏定义使用
A:宏定义
-D DEBUG
-D DEBUG=[value]
CFLAGS=
hello world
1 + 9 = 10
CFLAGS=-D DEBUG
hello world
1 + 9 = 10
Debug is defined
Debug is defined as true
CFLAGS=-D DEBUG=1
hello world
1 + 9 = 10
Debug is defined
Debug is defined as true
CFLAGS=-D DEBUG=0
hello world
1 + 9 = 10
Debug is defined
2. ifeq的使用
用来作条件编译
3. 链接参数
-L.:指定库搜索路径
-l(小写L) :指定链接库名称
-I:指定头文件搜索路径
4. 特殊规则
$@:目标文件
$^:所有依赖
$<:第一个依赖
三、 编译:
通过make命令进行编译
编译前目录:
.
.
|-- Makefile
|-- lib
| |-- include
| | `-- math_method.h
| `-- src
| `-- math_method.c
`-- main.c
编译后目录:
.
|-- Makefile
|-- a.out
|-- lib
| |-- include
| | `-- math_method.h
| `-- src
| `-- math_method.c
|-- libmath_method.a
|-- libmath_method.so
|-- main.c
`-- math_method.o
四、源码:
LIB_A_SUPPORT=y
LIB_SO_SUPPORT=y
CC=gcc
ifeq ($(LIB_A_SUPPORT), y)
LIBRARY=-L. -Wl,-dn -lmath_method -Wl,-dy -lgcc_s
endif
ifeq ($(LIB_SO_SUPPORT), y)
LIBRARY=-L. -Wl,-dy -lmath_method -Wl,-dy -lgcc_s
endif
INCLUDE=-I./lib/include
CFLAGS=
TARGET=a.out
ifeq ($(LIB_SO_SUPPORT), y)
DEPEND_TARGET += libmath_method.so
endif
ifeq ($(LIB_A_SUPPORT), y)
DEPEND_TARGET += libmath_method.a
endif
LIB_SRCS=$(wildcard ./lib/src/*.c)
LIB_NDIR_SRCS=$(notdir $(LIB_SRCS))
LIB_OBJ=$(patsubst %.c, %.o, $(LIB_NDIR_SRCS))
$(TARGET): $(DEPEND_TARGET)
gcc -o $@ main.c $(LIBRARY) $(INCLUDE) $(CFLAGS)
$(LIB_OBJ): $(LIB_SRCS)
echo $(LIB_SRCS) "f"$(LIB_OBJ)
$(CC) -fPIC -c $(LIB_SRCS)
ifeq ($(LIB_A_SUPPORT), y)
libmath_method.a: $(LIB_OBJ)
ar cr $@ $^
ranlib $@
endif
ifeq ($(LIB_SO_SUPPORT), y)
libmath_method.so: $(LIB_OBJ)
$(CC) -shared -o $@ $^
endif
.PHONY:
clean:
-rm -rf *.o *.a *.so
-rm $(TARGET)
main.c:
#include <stdio.h>
#include "math_method.h"
int main(int arc, char *argv[])
{
printf("hello world\n");
printf("%d + %d = %d\n", 1, 9, math_add(1, 9));
#ifdef DEBUG
printf("Debug is defined\n");
#endif
#if DEBUG
printf("Debug is defined as true\n");
#endif
return 0;
}
math_method.c:
#include <stdio.h>
int math_add(int a, int b)
{
return a + b;
}
int math_sub(int a, int b)
{
return a - b;
}
math_method.h:
#ifndef __MATH_METHOD_H__
#define __MATH_METHOD_H__
int math_add(int a, int b);
int math_sub(int a, int b);
#endif