Zephyr--添加自己的库(文件)

创建自己的文件

在zephyr/drivers路径下创建my_add文件夹

mkdir my_add

在my_add文件夹下创建:

# CMakeLists.txt

# Kconfig

# test.c

在CmakeLists.txt中添加:

zephyr_sources(test.c)#添加我自己的.c文件。

例子比较简单,Kconfig文件就不用写什么配置了。

编写简单的test.c文件,我这里就写了一个简单的函数:

#include "drivers/test.h"

int add(int a, int b)
{
	return (a + b);
}

把自己的文件添加到与自己文件同路径下的CMakeLists.txt中:

#路径
zephyr/drivers/CMakeLists.txt
add_definitions(-D__ZEPHYR_SUPERVISOR__)

add_subdirectory(interrupt_controller)
add_subdirectory(misc)
add_subdirectory(pcie)
add_subdirectory(disk)
add_subdirectory(usb)
add_subdirectory(usbc)
add_subdirectory(my_add) #在zephyr/drivers中添加我自己的文件夹

在zephyr/include/drivers中添加test.h

#ifndef __TEST_H_
#define __TEST_H_

int add(int,int);

#endif

测试

在zephyr/sample/中创建my_test文件夹

mkdir my_test

在CMakeLists.txt中添加最基本的:

cmake_minimum_required(VERSION 3.20.0) #指明对cmake的版本要求
 
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})#使用 Zephyr 基本环境设置搜索 Zephyr ZEPHYR_BASE然后使用正常的搜索路径
#上面说的两种应用程序结构方式,都是采用这种搜索模式
 
project(hello_world) #项目的名字
 
target_sources(app PRIVATE src/main.c) #添加可执行文件(目标文件),注意必须在find——package之后

在src文件夹中创建main.c

/*
 * Copyright (c) 2012-2014 Wind River Systems, Inc.
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <zephyr.h>      
#include <sys/printk.h>
#include <drivers/test.h> /*添加头文件*/
void main(void)
{
   	int sum = add(3,5);  /*调用my_add中的add函数*/
	printk("my test! %s
", CONFIG_BOARD);
	printk("sum = %d
",sum);
}

编译与运行

west build -b qemu_x86 samples/my_test/ -p

west build -t run

结果:

经验分享 程序员 微信小程序 职场和发展