将结构声明为 extern 并在不同文件中使用相同的变量

declaring struct as extern and using same variable in different file

我需要一些有关使用结构和外部表达式的说明。我的代码是这样的。

cfile.c

volatile struct my_struct{
        char *buf;
        int size;
        int read;
        int write;
    }rx,tx;

void foo1()
{
    rx.size = 256;
    rx.buf = (char *)malloc(rx.size * sizeof(char));
    rx.read = 0;
    rx.write = 0;
    tx.size = 256;
    tx.buf = (char *)malloc(tx.size * sizeof(char));
    tx.read = 0;
    tx.write = 0;
}

xyzFile.c

//extern the structure

在此函数中使用结构变量

void foo2(void)
{
        int next;

        next = (rx.write + 1)%rx.size;
        rx.buf[rx.write] = data;
        if (next != rx.read)
            rx.write = next;
}

在这个函数 foo 中,我得到了这个数据 rx.buf 并且想在 cfile.c 中使用这个数据。我该怎么做?

提前致谢。

引入一个header,例如myheader.h.
里面声明数据类型,声明外部变量。

#ifndef MYHEADER_H
#define MYHEADER_H

struct my_struct{
    char *buf;
    int size;
    int read;
    int write;
};

extern struct my_struct rx;
extern struct my_struct tx;
#endif

在您的代码文件 both/all 中包含 header

#include "myheader.h"

别忘了在其中一个代码文件中定义变量,
但不要使用所示代码中的 "shorthand" 类型声明和变量定义组合。
只需使用 header 中声明的类型,注意缺少 extern.
IE。将其替换为 cfile.c

volatile struct my_struct{
    char *buf;
    int size;
    int read;
    int write;
}rx,tx;    

通过这个,但只在这个.c文件中。

struct my_struct rx;
struct my_struct tx;