我需要一些关于使用结构和外部的澄清。我的代码是这样的。
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;
}
在这个函数中,我正在rx.buf
获取这些数据,并希望在cfile.c
中使用这些数据。我该怎么做?
提前谢谢。
引入一个标头,例如 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
在两个/所有代码文件中都包含标头
#include "myheader.h"
不要忘记仍然只在其中一个代码文件中定义变量,
但不要使用所显示代码中类型声明和变量定义的"速记"组合。
只需使用标头中声明的类型,请注意缺少extern
。
即在 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;