c - 将映射地址声明为外部地址

标签 c embedded mapping extern

我正在尝试绘制一些位置的 map ,这是我的代码示例。我想将 porta 和 ddra 声明为外部变量,以便我可以在文件之间共享它们。

typedef union _porta
{
  byte REGISTER;
  struct 
  {
     unsigned PA0:1;
     unsigned PA1:1;
     unsigned PA2:1;
     unsigned PA3:1;
     unsigned PA4:1;
     unsigned PA5:1;
     unsigned PA6:1;
     unsigned PA7:1;

  };
}PORTA;


typedef union _da
{
  byte REGISTER;
  struct 
  {
     unsigned  DA0:1;
     unsigned  DA1:1;
     unsigned  DA2:1;
     unsigned  DA3:1;
     unsigned  DA4:1;
     unsigned  DA5:1;
     unsigned  DA6:1;
     unsigned  DA7:1;

  };
}DDRA;


#define porta      (*(( volatile PORTA *)0x22))
#define  ddra        ( *(( volatile DDRA *)0x21) ) 
// Here in the same header want to declare porta and ddra as an extern variables I can use outside 

最佳答案

简单地将定义和 typedef 放入头文件中,并将其命名为“xxx_registers.h”或类似名称(其中 xxx 是您的 MCU)。通常就是这样做的。

但是,您应该将 typedef 命名为 DDRA_t,然后命名为 #define DDRA ... volatile DDRA_t*。习惯上始终使用大写字母作为寄存器名称。

重要提示:确保编译器中禁用严格别名!否则这样的代码可能会以可怕的方式崩溃。这主要是 gcc 编译器的问题,但其他编译器可能会以类似的功能失调方式处理严格别名。对于 gcc,在编写嵌入式系统时始终使用 -fno-strict-aliasing 进行编译,否则该编译器将无法使用。

请注意,位域是不可移植的且危险的,因此不能保证此代码可以在其他编译器上运行。使用按位运算符来访问各个位比位字段更好、更安全。

关于c - 将映射地址声明为外部地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49184591/

相关文章:

arm - STM32编程技巧和问题

c - 如何在编译期间检查 C 函数的有效输入?

c - 在嵌入式 c 中使用 printf

c# - 流畅的 nhibernate 查询需要很长时间才能使用分页对映射公式进行排序

c++ - 一些测试,看看使用指针迭代和使用索引迭代生成的代码是否不同?

c - 给定数据类型的算术运算成本是否随操作数值而变化?

c - https 使用 libcurl vs golang

c++ - 如何使用 Windows API 检索 HD 供应商/序列号

python - BLAST 数据库分配错误

c# - EmitMapper 的集合列表映射问题