Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross referencing included headers in c++ program

Tags:

I am curious about a scenario set up like the following example:

Here is code that would be placed in a file called Header1.h:

#ifndef HEADER1_H #define HEADER1_H  #include "Header2.h"  class Class1 {  Class2 class2Instance; };  #endif 

Here is code that would be placed in a file called Header2.h:

#ifndef HEADER2_H #define HEADER2_H  #include "Header1.h"  class Class2 {  Class1 class1Instance; };  #endif 

I get error messages when I do this (because of the includes I assume), but it feels like I would need to do this in order to include each of the objects in the separate classes. Can anyone help me accomplish this, what am I doing wrong?

like image 626
phoganuci Avatar asked Sep 15 '09 20:09

phoganuci


People also ask

Which is correct to include header file in C program?

In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”. All the header file have a '. h' an extension.

Can C++ include C headers?

If you are including a C header file that isn't provided by the system, you may need to wrap the #include line in an extern "C" { /*... */ } construct. This tells the C++ compiler that the functions declared in the header file are C functions.

How many header files are there in C?

There are 19 header files in the Standard C Library. All files have the . h file extension.

Why does C have headers?

The header file eliminates the labor of finding and changing all the copies as well as the risk that a failure to find one copy will result in inconsistencies within a program. In C, the usual convention is to give header files names that end with .


2 Answers

The problem is that the size of Class1 depends on Class2, and vice-versa. Therefore, there's no way to calculate the size for either one. Forward-declare one of the classes, and change one of the attributes to be a pointer or reference:

#ifndef HEADER2_H #define HEADER2_H  class Class1; class Class2 {  Class1 *class1Instance;  // or  Class1 &class1Instance; };  #endif 
like image 158
John Millikin Avatar answered Oct 09 '22 10:10

John Millikin


file:header1.h

#ifndef HEADER1_H #define HEADER1_H  class Class2; // no need to include Header2  class Class1 {     Class2* class2Instance; }  #endif 

file:header1.cpp

#include "header2.h" // do include Header2 here, otherwise you will get errors 

adapted from here

like image 24
sadhen Avatar answered Oct 09 '22 10:10

sadhen