0

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

1
  • put both the header and the function in one header file, nd #include it in in both file1.c and file2.c Commented Oct 8, 2014 at 18:00

2 Answers 2

1

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_ */
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.