0

is it posibble in C, that you define a structure in one .c file, but use it in another? Basically, I would like to use my List that I have already created in another program. But I would like to use diffrent structures.

I've 3 files:

main.c -- another program, where I want to use the list

list.c -- code of the list

head.h -- header to bind them

In main.c:

#include <stdio.h>
#include <stdlib.h>

typedef struct cell{
int x;
cell next;
}TCell;

typedef struct{
TCell first;
int lenght;
}List;

#include "head.h"

int main()
{
TCell *c
c->x = 5;
List *l;
init(l);
add(l,c)
c = get();
return 0;
}

head.h:

#ifndef HEAD_H_
#define HEAD_H_
void init(List *l);
void add(List *l, TCell *c);
TCell get();    
(...)
#endif 

list.c

#include <stdio.h>
#include <stdlib.h>

#include "head.h"

typedef struct{
TCell first;
int lenght;
}List;

void init(List *l){ (...) }
void add(List *l, TCell *c) { (...) }
TCell get() { (...) }
(...)

But when i try to compile it, it doesn't work, because it is missing the TCell in head.h and list.c, and the List in head.h

So, is there a possibility to have just one definition of TCell in the main.c, so whenever i change its inner variables, it will still work?

Martafix
  • 13
  • 3

1 Answers1

1

Make this your head.h:

#ifndef HEAD_H_
#define HEAD_H_

typedef struct cell
{
    int  x;
    cell next;
} TCell;

typedef struct
{
    TCell first;
    int   lenght;
} List;

void init(List *l);
void add(List *l, TCell *c);
TCell get();    

...

#endif 

And remove the typedef of List and TCell from list.c and main.c, because you only need to define a type once.

Header files are meant to contain your shared type definitions.

Here's an entry of the famous C-FAQ that may help. I advise you to read through this whole FAQ it will teach you a lot of things about C and will save you a lot of time.

meaning-matters
  • 21,929
  • 10
  • 82
  • 142