首先,创建一个Kbuild文件夹,目录层次如下图
首先介绍下每个文件的作用
一.
Kconfig文件
1 menu TEST_KBUILD
2 config ARM
3 tristate "enable gcc arm"
4 config x86
5 bool "enable gcc x86"
6 config TEST
7 bool "enable test.c"
8 config MYPRINT
9 bool "enable myprint.c"
10 help
11 this is a test
12 endmenu
~
执行make menuconfig
二.
hello.c(内有main函数)
1 #include<stdio.h>
2 #include"autoconf.h"
3 void main()
4 {
5 #ifdef CONFIG_ARM
6 printf("ARM PLAT!\n");
7 #endif
8 #ifdef CONFIG_x86
9 printf("x86 PLAT!\n");
10 #endif
11 #ifdef CONFIG_TEST
12 test();
13 #endif
14 #ifdef CONFIG_MYPRINT
15 my_print();
16 #endif
17 }
三.
test.c(main里面调用的test函数)
1 #include<stdio.h>
2 void test()
3 {
4 printf("this is test!\n");
5 }
~
四.
myprint.c(main里面调用的my_print函数)
1 #include<stdio.h>
2 void my_print()
3 {
4 printf("this is myprint!\n");
5 }
~
五.
tools文件夹,里面包括conf 和 mconf两个可执行文件
conf和mconf从内核/linux-2.6.32.2/scripts/kconfig/目录下拷贝过来的,后面图形界面编译可用(类似内核make menuconfig)
include/config/
include/linux/
注意:需手动创建,然后敲./tool/conf -s Kconfig,会将相关头文件和宏定义放进去
类似内核/linux-2.6.32.2/include/下面的文件夹,用来存放生成的头文件和宏定义
linux/的autoconf.h
config/auto.conf
六.
Makefile
1 TARGET=hello
2 include ./include/config/auto.conf
3 LDFLAGS= -I./include/linux
4 obj-y := hello.c
5 obj-$(CONFIG_TEST) += test.c
6 obj-$(CONFIG_MYPRINT) += myprint.c
7
8 all:$(TARGET)
9 $(TARGET):$(obj-y)
10 gcc $(LDFLAGS) -o $@ $(obj-y)
11
12 defconfig:
13 ./tools/conf Kconfig
14 ./tools/conf -s Kconfig
15 menuconfig:
16 ./tools/mconf Kconfig
17 ./tools/conf -s Kconfig
18 clean:
19 rm $(TARGET)
20
分析Makefile
生成目标文件hello,Makefile用include指定包含的宏定义文件,确定该文件是否编译,如:obj-$(CONFIG_TEST) += test.c,当CONFIG_TEST宏没开时,test.c不编译。类是内核的Makefile控制文件编译与否。
LDFLAGS= -I./include/linux 指定编译的hello.c查找的头文件路径
menuconfig中的./tools/mconf Kconfig用于界面生成宏定义控制,类似内核make menuconfig,选择宏开关与否。
./tools/conf -s Kconfig用于生成include/config 和include/linux下的头文件和宏定义
举个例子:
执行make menuconfig
选择enable gcc test.c不编译,然后保存
查看include/linux/autoconf.h
查看include/config/auto.conf
可见和test相关的宏定义都没有了
执行make
可见test.c没有编译
运行hello程序
打印结果
说一下make defconfig (即./tools/conf Kconfig)
是一步一步确定是否开启相关宏定义的
是不是很简单
首先拷贝内核的mconf和conf到指定目录下,然后自己编写Makefile和Kconfig就OK了。