0

I need some clarification about using structure and externs. My code is like this.

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

Use structure variable in this function

void foo2(void)
{
        int next;

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

In this function foo i'm getting this data rx.buf and wanted to use this data in cfile.c. How can i do that?

Thanks in advance.

Devjeet Mandal
  • 345
  • 1
  • 4
  • 23

1 Answers1

2

Introduce a header, e.g. myheader.h.
Inside declare the data type and declare the external variables.

#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

Inside both/all of your code files include the header

#include "myheader.h"

Do not forget to still define the variables in exactly one of the code files,
but do not use the "shorthand" combination of type declaration and variable definition from your shown code.
Just use the type as declared in the header, note the absence of extern.
I.e. replace this inside cfile.c

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

by this, but only in this one .c file.

struct my_struct rx;
struct my_struct tx;
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • Throws an error `Symbol rx multiply defined` – Devjeet Mandal Jul 03 '18 at 19:59
  • On which line in which file and how often do you have that line in your code files? – Yunnosch Jul 03 '18 at 20:00
  • gives error in object file. The files where i have included the header file – Devjeet Mandal Jul 03 '18 at 20:04
  • Can you count the number of times you define the variable `rx`? To do that look for lines which do NOT have an `extern`. There must be only one such line in all code files together, i.e. only one in only one of the code files. The lines with `extern` can be as many as you like, as long as they are identical. That includes lines which include the header. – Yunnosch Jul 03 '18 at 20:06
  • There are exactly two files where i have defined the variable rx without extern. and included the header file in both of those files. – Devjeet Mandal Jul 03 '18 at 20:08
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/174290/discussion-between-yunnosch-and-devjeet-mandal). – Yunnosch Jul 03 '18 at 20:09