Friday, August 6, 2010

Circular Dependency - An Interesting Solution

During development of Cosmos programming language, I faced to many usual and unusual problems related to C programming language. One of them was circular dependency which I like the most. Imagine file a.c includes a.h, b.c includes b.h, a.h includes b.h, and b.h includes a.h.

This is usually solved by using at least an extra H file storing some common parts of a.h and b.h. But, I really didn't want this so I solved it in following way. Have in mind that this is a trivial example:

main.c
#include "a.h"
#include "b.h"

int main(){
 a * v1;
 b * v2;
 return 0;
}

a.h
#ifndef CO_A_H
#define CO_A_H

struct a_t;

#include "b.h"

typedef struct a_t {
 struct b_t * value;
} a;

#endif

a.c
#include "a.h"

b * a_b(a * self){
 return 0;
}

b.h
#ifndef CO_B_H
#define CO_B_H

struct b_t;

#include "a.h"

typedef struct b_t {
 struct a_t * value;
} b;

#endif

b.c
#include "b.h"

a * b_a(b * self){
 return 0;
}

No comments:

Post a Comment