通过多个文件传递全局指针以进行中断例程

Passing a global pointer through multiple files for an interrupt routine

我有两个问题。第一个是将中断例程放在与主文件分开的文件中(在定义其他函数的文件中)是个好主意吗?

第二个是,我如何传递来自不同文件的全局指针?为了让我自己更容易,指针是 "pointing" 指向全局变量的地址。

文件 1 mylib.c

unsigned char b;
unsigned char e;    //global variables used for the interrupt routine
unsigned char *bp =&b;
unsigned char *ep = &e;

文件 2 mylib.h

extern unsigned char e;
extern unsigned char b;
extern unsigned char *ep;
extern unsigned char *bp;

文件 3 main.c

#include "mylib.h"
use (e);
use (b);
use (*ep);
use (*bp);

它说指针在定义时没有定义? 对于这里提出的两个问题,我没有找到太多帮助,所以这就是我发布它的原因,找到答案会很有趣。

编译报告:

10 371 Specifier needed main.c
10 393 'use ' Identifier redefined main.c 
11 371 Specifier needed main.c
11 393 'use ' Identifier redefined main.c

is it a good idea to have an interrupt routine in a separate file from your main (?)

这不是C的要求,而是代码的组织问题。是的,将源代码分割成逻辑组是件好事。

将中断服务例程 (ISR) 及其相关函数和变量放在一个单独的文件中是个好主意。

how do i pass a global pointer from different files?

所有文件都可以访问全局标识符(变量、对象、函数),因为它是全局。诀窍是,特定的 .c 文件是否知道它?通过将 #include "mylib.h" 包含在 main.c 中,该代码可以根据标识符的 声明 识别标识符,例如 extern unsigned char *bp;.

同时考虑:

1) unsigned char b, e; 不需要在全局 space 中,因为其他 *.c 文件可以通过 unsigned char *bpunsigned char *ep 访问它们。参见 information hiding

2) 名称 bp, ep 很短,很可能与其他代码冲突。推荐一个暗示他们 "home".

的前缀

3) 指针可能应该是常量并指向 volatile 数据,因为它们是 ISR 的一部分。

    // mylib.h
    extern volatile unsigned char * const mylib_ep;
    extern volatile unsigned char * const mylib_bp;

    // mylib.c
    static volatile unsigned char b;
    static volatile unsigned char e;
    volatile unsigned char * const mylib_bp = &b;
    volatile unsigned char * const mylib_ep = &e;

    // main.c
    #include "mylib.h"
    // do not use (e);
    // do not use (b);
    use (*mylib_ep);
    use (*mylib_bp);

it states that pointers aren't defined when they are?

指针在mylib.h声明。指针在 mylib.c.

定义

从设计的角度来看,我不会让其他文件访问上述数据。相反,我会创建一个 getset 函数。我假设这两个变量需要 read/written 以 atomic 的方式:两者 read/written 一起没有机会在 get/set 期间调用 ISR .

void mylib_b_e_get(char *b, char *e);
void mylib_b_e_set(char b, char e);

关于 use 的编译报告反映伪代码函数 use() 尚未声明或定义。