Course contentsShow
← C
Lesson 794 of 1,21911. The Preprocessor and BuildFree lesson

Circular dependency issues

Circular dependency issues

What you'll learn: How to recognize and prevent the "infinite loop" that occurs when two header files try to include each other at the same time.

The "After You" Paradox

Imagine two overly polite people standing at a doorway. Person A says, "I won't go through until Person B goes first." Person B says, "I won't go through until Person A goes first." They stand there forever, and nothing gets done.

In C, a circular dependency happens when file_a.h contains #include "file_b.h", but file_b.h also contains #include "file_a.h". When the preprocessor tries to build your program, it starts reading File A, sees it needs File B, jumps to File B, sees it needs File A, and gets stuck in an endless cycle. Eventually, the compiler gives up and throws a confusing error.

Why it happens

Circular dependencies usually creep in when two data structures need to know about each other. For example, a User struct might need to know about a Post struct, and the Post needs to know who the User is.

If you just blindly #include both headers, you create a loop:

/* user.h */
#include "post.h" 
struct User {
    struct Post *last_post;
};

/* post.h */
#include "user.h"
struct Post {
    struct User *author;
};

When the compiler looks at user.h, it tries to resolve post.h first. But post.h tells it to go back to user.h. The compiler hasn't finished defining User yet, so it crashes into a wall.

The Solution: Forward Declarations

You can break this cycle using a forward declaration. Instead of including the entire header file, you simply tell the compiler: "Hey, a struct with this name exists. I'll give you the details later."

If you only use a pointer to a struct (which is common in linked data), the compiler doesn't need to know the full size or contents of that struct yet. It just needs to know it's a valid name.

/* post.h */
// Instead of #include "user.h", we use a forward declaration:
struct User; 

struct Post {
    struct User *author; // The compiler is happy because it knows User is a struct
};

By removing the #include from one side of the circle, you break the loop and allow the preprocessor to finish its job.

Key takeaway

Circular dependencies happen when headers include each other; break the loop by using forward declarations instead of #include whenever possible.