3. 编写第一个应用程序
任务目标
在NuttX源码树中创建一个自定义应用程序hello,通过Makefile集成到NuttX构建系统,编译烧录后在NSH命令行中执行该程序并输出Hello, NuttX!。
环境准备
本案例假设已具备可编译的NuttX源码树和已配置好的sim模拟器平台(或任意真实开发板平台)。以下路径均相对于NuttX源码根目录。
实现步骤
1. 创建应用目录与源码
在apps/examples/下新建hello目录,创建hello_main.c:
#include <nuttx/config.h>
#include <stdio.h>
int main(int argc, FAR char *argv[])
{
printf("Hello, NuttX!\n");
return 0;
}
2. 编写Makefile
在hello目录下创建Makefile,内容如下:
include $(APPDIR)/Make.defs
PROGNAME = hello
PRIORITY = SCHED_PRIORITY_DEFAULT
STACKSIZE = 2048
MODULE = $(CONFIG_EXAMPLES_HELLO)
include $(APPDIR)/Application.mk
3. 添加Kconfig配置
在hello目录下创建Kconfig,用于构建系统菜单配置:
config EXAMPLES_HELLO
tristate "Hello World example"
default n
---help---
Enable the hello world example
4. 注册到构建系统
编辑apps/examples/Kconfig,在文件末尾添加:
source "$APPSDIR/examples/hello/Kconfig"
编辑apps/examples/Make.defs,添加:
ifneq ($(CONFIG_EXAMPLES_HELLO),)
CONFIGURED_APPS += $(APPDIR)/examples/hello
endif
编译与运行
cd nuttx
make distclean
./tools/configure.sh sim:nsh
make menuconfig
在menuconfig中进入Application Configuration → Examples,勾选Hello World example,保存退出。然后编译:
make -j$(nproc)
运行模拟器:
./nuttx
在NSH提示符下执行:
nsh> hello
验证方法
执行hello命令后,终端应显示:
Hello, NuttX!
若输出与上述一致,说明应用已正确集成到NuttX构建系统并可在NSH中运行。若提示hello: command not found,请检查Kconfig是否已正确注册、menuconfig中是否已启用该选项,以及是否重新完整编译。
常见问题
- 编译时找不到
hello_main.c:确认文件名与Makefile中PROGNAME对应,NuttX默认查找PROGNAME同名的_main.c文件。 - menuconfig中看不到选项:检查
apps/examples/Kconfig的source路径是否正确,并确认APPSDIR环境变量已设置。 - 运行后无输出:确认
STACKSIZE足够(2048通常足够),或检查串口/控制台配置是否正确。