编译内核模块 error: implicit declaration of function ‘copy_from_user’

1.问题出现

  我在编译内核模块时使用了如下代码段

    if (copy_from_user(&led_num, buf, len))
    {
        return -EFAULT;
    }

makefile如下

#General Purpose Makefile for cross compile Linux Kernel module
ifneq ($(KERNELRELEASE),)
obj-m := led.o  #+=是连接字符串
else

ARCH := arm    
CROSS_COMPILE := /usr/local/arm/arm-linux-gnueabihf-4.9/bin/arm-linux-gnueabihf-
KERN_DIR := /home/zqh/lichee/linux-zero-4.14.y  #选择内核路径
PWD :=$(shell pwd)   #当前路径

all:
        make ARCH=$(ARCH) CROSS_COMPILE=$(CROSS_COMPILE) -C $(KERN_DIR) M=$(PWD) modules
        $(CROSS_COMPILE)gcc main.c -o test_led
clean:                                   
        rm -f *.ko *.o *.symvers *.mod.c *.mod.o *.order .*.o.ko.cmd .*.ko.cmd .*.mod.o.cmd .*.o.cmd
        
endif
 

在编译时出现以下问题

/home/zqh/lichee/Driver_learn/led_driver/led.c: In function ‘led_write’:
/home/zqh/lichee/Driver_learn/led_driver/led.c:83:2: error: implicit declaration of function ‘copy_from_user’ [-Werror=implicit-function-declaration]
  if (copy_from_user(&led_num, buf, len))
  ^
cc1: some warnings being treated as errors
scripts/Makefile.build:320: recipe for target '/home/zqh/lichee/Driver_learn/led_driver/led.o' failed
make[2]: *** [/home/zqh/lichee/Driver_learn/led_driver/led.o] Error 1
Makefile:1507: recipe for target '_module_/home/zqh/lichee/Driver_learn/led_driver' failed
make[1]: *** [_module_/home/zqh/lichee/Driver_learn/led_driver] Error 2
make[1]: Leaving directory '/home/zqh/lichee/linux-zero-4.14.y'
Makefile:12: recipe for target 'all' failed
make: *** [all] Error 2

2.问题解决

 我当时是安装别人的教程来写的程序。我百度了这个问题,有的人指出要添加

#include <asm/uaccess.h> 

但是我添加了发现也是没用。

但当我点击这个uaccess.h时,自动跳转到了 linux/uaccess.h.所以我发现了问题所在

#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/io.h>
#include <linux/uaccess.h>

现在编译即可成功。

原文地址:https://www.cnblogs.com/ZQQH/p/8622891.html