Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular dependency between C header files

Tags:

c

header

Does anybody have any tip how to handle the symbolic constants and types definition in large program in a system manner to avoid circular dependencies between the header files? I have an idea to define one header file which will contain all structs, unions and enum types definitions and another header file which will contain all symbolic constants definitions. But I have doubts as far as this solution regarding to implementation hiding. Thank you for any ideas.

like image 919
Steve Avatar asked Sep 11 '17 07:09

Steve


People also ask

How do you fix a circular dependency problem?

There are a couple of options to get rid of circular dependencies. For a longer chain, A -> B -> C -> D -> A , if one of the references is removed (for instance, the D -> A reference), the cyclic reference pattern is broken, as well. For simpler patterns, such as A -> B -> A , refactoring may be necessary.

What is circular dependency in C?

In software engineering, a circular dependency is a relation between two or more modules which either directly or indirectly depend on each other to function properly. Such modules are also known as mutually recursive.

How do you avoid circular dependencies?

To reduce or eliminate circular dependencies, architects must implement loose component coupling and isolate failures. One approach is to use abstraction to break the dependency chain. To do this, you introduce an abstracted service interface that delivers underlying functionality without direct component coupling.

Can DLL be circular?

It can't, as you can't create circular dependencies.


1 Answers

You can separate out the typedef statements from the actual struct definitions and place them before including the other headers. This way if your datatype foo contains a member of type bar *, it doesn't need the definition of bar straight away - it'll be happy enough knowing that it's a valid datatype that will get resolved later.

#ifndef FOO_H
#define FOO_H

typedef struct foo_s foo;

#include "bar.h"

struct foo_s
  {
  bar *my_bar;
  };
#endif

.

#ifndef BAR_H
#define BAR_H

typedef struct bar_s bar;

#include "foo.h"

struct bar_s
  {
  foo *my_foo;
  };
#endif
like image 134
Chris Turner Avatar answered Oct 05 '22 23:10

Chris Turner