Adrien Neveu
Adrien Neveu

Reputation: 827

What is the correct way to include headers between two files in C

I guess that's a pretty dumb question, but I'm facing a little problem in my C program:

Let's say I have file1.c and file2.c

I'm using in file1.c and file2.c a struct declared in file2.c I'm also using file1.c functions inside file2.c

So what I did is that I put #include "file1.h" in file2.h and #include "file2.h" in file1.h... But I have an infinite loop when compiling.

How can I fix this? Thanks

Upvotes: 0

Views: 295

Answers (2)

sfstewman
sfstewman

Reputation: 5677

Include guards, as mentioned by @downhillFromHere, are one answer. All header files should have include guards, unless you have a very good reason otherwise.

However, your description doesn't make it clear why you need file1.h to include file2.h and vice versa. Header files describe an interface. If the interfaces are dependent, then you should think about combining them into a single header: file.h. If the interfaces described in file1.h and file2.h are independent, then they shouldn't include each other. The proper way to expose independent interfaces is to have file1.c and file2.c include both headers.

In both file1.c and file2.c:

#include "file1.h"
#include "file2.h"

This keeps the interfaces decoupled, which allows you to reason about the independent interfaces separately, reduces mistakes, and can greatly reduce compile time.

Upvotes: 1

downhillFromHere
downhillFromHere

Reputation: 1977

You need to use include guard in both file1.h and file2.h. Something like

#ifndef FILE1_H_
#define FILE1_H_

/* ...
 * code
 */

#endif /* FILE1_H_ */

Upvotes: 1

Related Questions