基于STM32CubeMX的C/C++混合编译
写在前面
本文介绍一种简单的思路,让CubeMX生成的工程在支持C/C++混合编译还能继续使用CubeMX修改维护底层配置。
实现过程
一、CubeMX生成工程
二、新建三个CPP文件
新建一个Sys文件夹,然后在里面新建三个cpp文件(位置、名称不指定,后缀指定)。
三、往文件中写代码
task.cpp
/*
* @Description: task.cpp
* @Version: 0.1
* @Autor: ZhangRiven
*/
#include "task.hpp"
#include "x.h"
...
#include "xx.hpp"
...
/* Object Create */
RobotControl obj_Robot(&htim3, TIM_CHANNEL_1, TIM_CHANNEL_2, TIM_CHANNEL_3);//定义机器人对象
_LED obj_LED0(LED0_GPIO_Port, LED0_Pin, GPIO_PIN_RESET);//定义LED灯对象
_KEY obj_KEY0(KEY1_GPIO_Port, KEY1_Pin, 0);//定义按键对象
...
/* END */
/**
* @description: Task_Init包装了用于初始化的c/cpp代码
* @param {*}
* @return {*}
* @author: ZhangRiven
*/
void Task_Init()
{
/* Hardware Init BEGIN */
obj_Robot.Init();//对象初始化
...
/* END */
/* 初始化结束,关灯示意 */
obj_LED0.OFF();
/* END */
while(obj_KEY0.Read()==0)
{
obj_Robot.Patrol_Value_Handling();
}
delay_ms(1000);
}
/**
* @description: Task_Do包装了需要循环的c/cpp代码
* @param {*}
* @return {*}
* @author: ZhangRiven
*/
void Task_Do()
{
obj_LED0.ON();
obj_Robot.Stretch_out_hand();
delay_ms(1000);
...
obj_LED0.OFF();
obj_Robot.Back_hand();
delay_ms(1000);
...
}
task.h
/*
* @Description: task.h
* @Version: 0.1
* @Autor: ZhangRiven
*/
#ifndef __TASK_H
#define __TASK_H
#include "main.h"
#include "xxx.h"
...
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* C CODE BEGIN */
void Task_Init(void);//初始化函数声明,在main.c的while(1)前调用该接口
void Task_Do(void);//循环内容函数声明,在main.c的while(1)内调用该接口
/* C CODE END */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
task.hpp
/*
* @Description: task.hpp
* @Version: 0.1
* @Autor: ZhangRiven
*/
#ifndef __TASK_HPP
#define __TASK_HPP
#include "task.h"
#include "xxxx.hpp"
...
/* CPP CODE BEGIN */
extern RobotControl obj_Robot;//全局对象声明
extern ...
/* CPP CODE END */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* C CODE BEGIN */
//一般将用c编译的声明代码写在task.h中,而不是写在这
/* C CODE END */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
四、在main.c中调用接口
包含头文件
... /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "task.h" /* USER CODE END Includes */ ...
调用两个接口
...
/* USER CODE BEGIN 2 */
Task_Init();
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
Task_Do();
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
...
五、在task.cpp中写自己的实现
略
六、总结
简单讲 task.hpp向上对应用层C++代码声明task.cpp中的内容(全局变量、对象等); task.cpp的函数包装了C/C++代码,使用C++方式编译函数中的实现; task.h向下对CubeMX生成的底层代码声明以C的方式编译两个函数接口,使在main.c中能调用到这两个函数。
