我想在Ubuntu中编译下面的程序。 但我不断收到错误:“stdio.h:没有这样的文件或目录”错误。
#include <stdio.h> int main(void) { printf("Hello world"); }
我的makefile是:
obj-m += hello.o all: make -I/usr/include -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
您的程序构建方式是构建内核模块而不是c程序应用程序的方式。 而stdio.h
在内核开发的环境中不存在,所以这就是为什么你得到的错误:
error: "stdio.h: No such file or directory" error
1)如果你想建立一个Linux应用程序,那么你的Makefile是错误的:
你应该修改你的Makefile
使用下面的Makefile:
all: hello test: test.c gcc -o hello hello.c clean: rm -r *.o hello
2)如果你想建立一个内核模块,那么你的C代码是错误的
stdio.h
。 它不存在于内核开发的环境中,所以这就是为什么你会得到错误 main()
printf()
INSTEAD使用stdio.h
,你必须使用下面的include
#include <linux/module.h> /* Needed by all modules */ #include <linux/kernel.h> /* Needed for KERN_INFO */
INSTEAD使用int main() {
,你必须使用
int init_module(void) {
INSTEAD使用printf()
使用printk()
使用下面的hello模块而不是你的hello代码
/* * hello-1.c - The simplest kernel module. */ #include <linux/module.h> /* Needed by all modules */ #include <linux/kernel.h> /* Needed for KERN_INFO */ int init_module(void) { printk(KERN_INFO "Hello world 1.\n"); /* * A non 0 return means init_module failed; module can't be loaded. */ return 0; } void cleanup_module(void) { printk(KERN_INFO "Goodbye world 1.\n"); }
有关内核模块开发的更多详细信息,请参阅以下链接
问题是你不能在内核中使用printf()
和stdio.h
,也不要使用main()
函数。 你需要printk()
和module.h
#include <linux/module.h> /* Needed by all modules */ #include <linux/kernel.h> int init_module(void) { printk(KERN_INFO "Hello world\n"); return 0; }
卸载时还应该有一个exit()
/ cleanup()
类型的函数。
void clean_module(void) { printk(KERN_INFO "Cleaning and exiting\n"); }
然后加载模块的功能:
module_init(init_module); module_exit(clean_module);
你的Makefile不正确,请看看其中的一个教程,例如: http : //mrbook.org/tutorials/make/
构建独立应用程序的最简单的Makefile应该如下所示:
all: hello hello: hello.o gcc hello.o -o hello hello.o: hello.cpp gcc -c hello.cpp clean: rm -rf *o hello
希望能帮助到你 !