Click here to Skip to main content
15,887,850 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If I have the following C code:
C++
struct A{struct B* element;}
struct B{struct A* element;}
main(){}

How do I compile it if when I declare the variable element of type "struct B*" this type wasn't defined yet?

And how would I make the makefile and the header files if I had those 2 structs defined in diferent files:

fileA.h:
C++
#ifndef _FILEA_H_
#define _FILEA_H_
#include "fileB.h"
struct A{struct B* element;}
#endif


fileB.h:
C++
#ifndef _FILEB_H_
#define _FILEB_H_
#include "fileA.h"
struct B{struct A* element;}
#endif


MAKEFILE:
CC = gcc
CFLAGS = -Wall -g
LDFLAGS = -lm

all: example

program.o: program.c

fileA.o: fileA.c fileA.h

fileB.o: fileB.c fileB.h

example: principal.o fileA.o fileB.o
	$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)


Can you guys help me? In both cases the compiler doesn't recognize the type inside the struct because it is only defined later.
Posted

First, write forward declaration of one of the struct, then fully define the other struct below, and, finally, fully define the first structure represented by the forward declaration above. The C syntax is pretty awkward; please see:
https://en.wikipedia.org/wiki/Struct_%28C_programming_language%29#Struct_initialization[^].

—SA
 
Share this answer
 
v2
Comments
CPallini 20-Jun-15 4:45am    
5.
Sergey Alexandrovich Kryukov 20-Jun-15 8:36am    
Thank you, Carlo.
—SA
Sergey already gave you the correct answer, I just add an example:

File a.h
C
#ifndef __A_H__
#define __A_H__
struct A; // forward declaration of A
struct B { struct A * element; };
#endif // __A_H__

File b.h
C
#ifndef __B_H__
#define __B_H__
struct B; // forward declaration of B
struct A { struct B * element; };
#endif // __B_H__

File m.c
C
#include "a.h"
#include "b.h"
int main()
{
  struct A a;
  struct B b;
  a.element = &b;
  b.element = &a;
  return 0;
}




An alternative would be putting forward declarations in the C source file, before actually including the headers:
C
#ifndef __A_H__
#define __A_H__
// requires the forward declaration of A
struct B { struct A * element; };
#endif // __A_H__


C
#ifndef __B_H__
#define __B_H__
// requires the forward declaration of B
struct A { struct B * element; };
#endif // __B_H__


C
// forward declarations
struct A;
struct B;
// headers
#include "a.h"
#include "b.h"

int main()
{
  struct A a;
  struct B b;
  a.element = &b;
  b.element = &a;
  return 0;
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900