在 STM32 上使用 C++

2020-01-07 19:19发布

本帖最后由 tyustli 于 2019-6-8 14:04 编辑

在 STM32 上使用 C++
如何使用在搭载了 RT-Thread 系统的 STM32 平台上使用 C++ ,这里介绍了包括 C++ 的配置和应用等。并给出了在意法半导体 STM32F411 nucleo 开发板上验证的代码示例。
硬件平台简介
本文基于意法半导体 STM32F411 nucleo 开发板,给出了 C++ 的具体应用示例代码,由于 RT-Thread 上层应用 API 的通用性,因此这些代码不局限于具体的硬件平台,用户可以轻松将它移植到其它平台上。
STM32F411 nucleo 是意法半导体推出的一款基于 ARM Cortex-M4 内核的开发板,最高主频为 100Mhz ,该开发板具有丰富的板载资源,可以充分发挥 STM32F411RE 的芯片性能。
throw_exceptions.png (18.04 KB, 下载次数: 0) 下载附件 2019-6-8 13:59 上传
附录 main.cpp 程序源码:
  1. /**
  2. * @file      main.cpp
  3. * @time      2019-6-8 13:31:39
  4. * @author    tyustli
  5. * @platform  w10 + mdk5 + rtthread 4.0.0
  6. */

  7. #include <rtthread.h>
  8. #include <rtdevice.h>
  9. #include <board.h>

  10. /* defined the LED0 pin: PA5 */
  11. #define LED0_PIN               GET_PIN(A, 5)

  12. int main(void)
  13. {
  14.    int count = 1;
  15.    /* set LED0 pin mode to output */
  16.    rt_pin_mode(LED0_PIN, PIN_MODE_OUTPUT);

  17.    while (count++)
  18.    {
  19.        rt_pin_write(LED0_PIN, PIN_HIGH);
  20.        rt_thread_mdelay(500);
  21.        rt_pin_write(LED0_PIN, PIN_LOW);
  22.        rt_thread_mdelay(500);
  23.    }

  24.    return RT_EOK;
  25. }
  26. using namespace rtthread;

  27. class tran
  28. {
  29. public:
  30.    void getnumber(int a, int b)
  31.    {
  32.        x = a;
  33.        y = b;
  34.    }
  35.    void out(tran & s)
  36.    {
  37.        rt_kprintf("x = %d, y = %d ", x, y);
  38.    }
  39. private:
  40.    int x, y;
  41. };

  42. int test_cpp(void)
  43. {
  44.    tran s;

  45.    s.getnumber(13, 54);
  46.    s.out(s);

  47.    return 0;
  48. }

  49. MSH_CMD_EXPORT(test_cpp, test cpp);

  50. #include<math.h>

  51. #define MIN_VALUE                 (1e-4)
  52. #define IS_DOUBLE_ZERO(d)         (abs(d) < MIN_VALUE)

  53. double div_func(double x, double y)
  54. {
  55.    if (IS_DOUBLE_ZERO(y))
  56.    {
  57.        throw y;                                           /* throw exception */
  58.    }

  59.    return x / y;
  60. }

  61. void throw_exceptions(void *args)
  62. {
  63.    try
  64.    {
  65.        div_func(6, 3);
  66.        rt_kprintf("there is no err ");
  67.        div_func(4, 0);                                   /* create exception*/
  68.        rt_kprintf("you can run here ");
  69.    }
  70.    catch(double)                                         /* catch exception */
  71.    {
  72.        rt_kprintf("error of dividing zero ");
  73.    }
  74. }

  75. MSH_CMD_EXPORT(throw_exceptions, throw cpp exceptions);
复制代码


友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。