ʹÓÃCMake¹¹½¨LinuxÄÚºËÄ£¿éµÄÉèÖÃÖ¸ÄÏ
ʹÓÃcmake¹¹½¨linuxÄÚºËÄ£¿éµÄÉèÖÃÖ¸ÄÏ
СÐò£º
CMakeÊÇÒ»ÖÖ¿çƽ̨µÄ¹¹½¨¹¤¾ß£¬¿ÉÒÔ×ÊÖú¿ª·¢Õ߸üÀû±ãµØÖÎÀíºÍ¹¹½¨ÏîÄ¿¡£ÔÚ¿ª·¢LinuxÄÚºËÄ£¿éʱ£¬Ê¹ÓÃCMake¿ÉÒÔ¼ò»¯ÉèÖúͱàÒëÀú³Ì£¬Ìá¸ß¿ª·¢Ð§ÂÊ¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃCMakeÀ´ÉèÖú͹¹½¨LinuxÄÚºËÄ£¿é£¬²¢¸½´ø´úÂëʾÀý¡£
Ò»¡¢×°ÖÃCMake
ÔÚ×îÏÈ֮ǰ£¬ÎÒÃÇÐèÒªÏÈ×°ÖÃCMake¡£ÔÚUbuntuÉÏ£¬¿ÉÒÔͨ¹ýÒÔÏÂÏÂÁî¾ÙÐÐ×°Öãº
sudo apt-get install cmake
µÇ¼ºó¸´ÖÆ
¶þ¡¢½¨ÉèCMakeLists.txtÎļþ
ÔÚLinuxÄÚºËÄ£¿éµÄÏîÄ¿¸ùĿ¼Ï£¬½¨ÉèÒ»¸öÃûΪCMakeLists.txtµÄÎļþ¡£Õâ¸öÎļþÐÎòÁËÏîÄ¿µÄ¹¹½¨ÉèÖúÍÒÀÀµ¹Øϵ¡£
ÒÔÏÂÊÇÒ»¸ö¼òÆÓµÄCMakeLists.txtÎļþʾÀý£º
# CMake×îµÍ°æ±¾ÒªÇó cmake_minimum_required(VERSION 3.10) # ÏîÄ¿Ãû³Æ project(kmodule_example) # ÄÚºËÄ£¿éÔ´Îļþ set(SOURCES example_module.c) # ±àÒëÑ¡Ïî add_compile_options(-Wall -Wextra) # ÄÚºËÄ£¿éµÄ¹¹½¨ÉèÖà add_module(${PROJECT_NAME} ${SOURCES})
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öʾÀýÖУ¬ÎÒÃÇÊ×ÏÈÖ¸¶¨ÁËCMakeµÄ×îµÍ°æ±¾ÒªÇ󣬲¢¸øÏîÄ¿ÃüÃûΪ”kmodule_example”¡£½Ó×Å£¬ÎÒÃǽ«ÄÚºËÄ£¿éµÄÔ´Îļþ(example_module.c)·ÅÔÚÒ»¸ö±äÁ¿ÖС£È»ºó£¬ÎÒÃÇÌí¼ÓÁËһЩ±àÒëÑ¡Ïî(-Wall -Wextra)£¬ÒÔÆôÓÃÖÒÑÔ²¢ÔöÌíÌØÁíÍâÖÒÑÔÐÅÏ¢¡£
×îºó£¬ÎÒÃÇʹÓÃadd_module()º¯ÊýÀ´½ç˵ÄÚºËÄ£¿éµÄ¹¹½¨ÉèÖᣵÚÒ»¸ö²ÎÊýÊÇÄÚºËÄ£¿éµÄÃû³Æ£¬µÚ¶þ¸ö²ÎÊýÊÇÄÚºËÄ£¿éµÄÔ´Îļþ¡£
Èý¡¢¹¹½¨ºÍ×°ÖÃÄÚºËÄ£¿é
ÔÚÏîÄ¿¸ùĿ¼Ï½¨ÉèÒ»¸öÃûΪbuildµÄĿ¼£¬ÔÚbuildĿ¼ÖÐÖ´ÐÐÒÔÏÂÏÂÁ
cmake .. make
µÇ¼ºó¸´ÖÆ
Ö´ÐÐcmakeÏÂÁƾ֤CMakeLists.txtÎļþÌìÉúMakefile£¬È»ºóÖ´ÐÐmakeÏÂÁîÀ´±àÒëÄÚºËÄ£¿é¡£
±àÒëÀֳɺ󣬿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÀ´×°ÖÃÄÚºËÄ£¿é£º
sudo make install
µÇ¼ºó¸´ÖÆ
ÄÚºËÄ£¿é½«±»×°Öõ½ÏµÍ³µÄ±ê׼λÖá£
ËÄ¡¢ÕûÀí¹¹½¨Ä¿Â¼
ÈôÊÇÐèÒªÕûÀí¹¹½¨±¬·¢µÄÖÐÑëÎļþ£¬¿ÉÒÔÖ´ÐÐÒÔÏÂÏÂÁ
make clean
µÇ¼ºó¸´ÖÆ
Õ⽫ɾ³ýÌìÉúµÄ¿ÉÖ´ÐÐÎļþºÍÔÝʱÎļþ¡£
Îå¡¢×ܽá
ÔÚ±¾ÎÄÖУ¬ÎÒÃÇÏÈÈÝÁËÔõÑùʹÓÃCMakeÀ´ÉèÖú͹¹½¨LinuxÄÚºËÄ£¿é¡£Í¨¹ýʹÓÃCMake£¬ÎÒÃÇ¿ÉÒÔ¸üÀû±ãµØÖÎÀíºÍ¹¹½¨ÏîÄ¿£¬Ìá¸ß¿ª·¢Ð§ÂÊ¡£Ï£ÍûÕâƪÎÄÕÂÄܹ»×ÊÖúÄãÔÚ¿ª·¢LinuxÄÚºËÄ£¿éʱԽ·¢ÇáËɵØʹÓÃCMake¡£
´úÂëʾÀý£º
ÒÔÏÂÊÇÒ»¸ö¼òÆÓµÄLinuxÄÚºËÄ£¿éʾÀý£¬ÃûΪexample_module.c£º
#include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> MODULE_LICENSE("GPL"); MODULE_AUTHOR("Your Name"); MODULE_DESCRIPTION("An example Linux kernel module"); static int __init example_module_init(void) { printk(KERN_INFO "Hello, World! "); return 0; } static void __exit example_module_exit(void) { printk(KERN_INFO "Goodbye, World! "); } module_init(example_module_init); module_exit(example_module_exit);
µÇ¼ºó¸´ÖÆ
Õâ¸öʾÀýÄÚºËÄ£¿éʵÏÖÁËÒ»¸ö¼òÆӵijõʼ»¯ºÍÍ˳öº¯Êý¡£ÔÚ³õʼ»¯º¯ÊýÖУ¬Ëü´òÓ¡Ò»ÌõÐÂÎÅ”Hello, World!”£»ÔÚÍ˳öº¯ÊýÖУ¬Ëü´òÓ¡Ò»ÌõÐÂÎÅ”Goodbye, World!”¡£
ͨ¹ýʹÓñ¾ÎÄÏÈÈݵÄCMakeÉèÖú͹¹½¨ÒªÁ죬±àÒëÕâ¸öʾÀýÄ£¿é½«»áºÜÊÇÀû±ã¡£
²Î¿¼Á´½Ó£º
CMake¹Ù·½Îĵµ£ºhttps://cmake.org/documentation/
LinuxÄÚºËÄ£¿é¿ª·¢Ö¸ÄÏ£ºhttps://www.kernel.org/doc/html/latest/kbuild/modules.html
ÒÔÉϾÍÊÇʹÓÃCMake¹¹½¨LinuxÄÚºËÄ£¿éµÄÉèÖÃÖ¸ÄϵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡