Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutual include in C++ .. how does it work? [duplicate]

Possible Duplicate:
Proper way to #include when there is a circular dependency?

I am pretty new to C++ and have the question asked in the title. Or more precisely: If A.h includes B.h and B.h includes A.h, I get an error message because "include# file "C:...\A.h" includes itself". File: B.h

I couldn't find a way to work around this, and my general setup pretty much requires that relation between those classes. Any possibility to make this work?

like image 665
ArniBoy Avatar asked Jul 22 '11 13:07

ArniBoy


People also ask

How does C include work?

The #include directive tells the C preprocessor to include the contents of the file specified in the input stream to the compiler and then continue with the rest of the original file. Header files typically contain variable and function declarations along with macro definitions.

How does Pragma once work?

In the C and C++ programming languages, #pragma once is a non-standard but widely supported preprocessor directive designed to cause the current source file to be included only once in a single compilation.

Should includes be in header or CPP?

In general, you should only include headers in . h files that are needed by those headers. In other words, if types are used in a header and declared elsewhere, those headers should be included. Otherwise, always include headers only in .

When Should header files be used?

Header File Inclusion Rules A header file should be included only when a forward declaration would not do the job. The header file should be so designed that the order of header file inclusion is not important. The header file inclusion mechanism should be tolerant to duplicate header file inclusions.


1 Answers

Use Include guards in your header files. http://en.wikipedia.org/wiki/Include_guard

#ifndef MYHEADER_H
#define MYHEADER_H

//add decls here 

#endif

This way if your header files are included more than once the compiler ignores them.

Also as a rule of thumb if you are including B.h which has A.h , it would be better to include A.h and B.h in your application instead of relying on the include of B.h.

Also only put declarations in header file .

Avoid Definitions at all costs in header files.

like image 172
xeon111 Avatar answered Sep 28 '22 03:09

xeon111