C++ Header files and compilation process

I have a question about c++ header files and their includes.

Consider the following scenario.

I have a following files and code inside :

Ah

class A
{
    // ...
};

A.cpp

#include "A.h"

// implementation of A

Bh

class B
{
    A object;
}

B.cpp

 #include "A.h"

 #include "B.h"

 /// implementation of B

When I try to build, the compiler gives an error in Bh, that can't recognize A, because I didn't include Ah

The question is why compiler compiles header files separately, if they are included in some cpp files and include preprocessor is doing the copy / paste full content of header file and header file content will be compiled with cpp file, where it included.


If Bh requires Ah, you should include Ah into Bh, because you can't assume that every time that Bh is included, Ah will be included before.

Of course, if you simply include Ah into Bh, you'll have Ah parsed twice (or more), so duplicate definitions and a bunch of errors, which is why you must also include header guards. See C++ #include guards for an explanation of header guards.


You might use header guards structure for both .h files:

#ifndef FILE_A_H
#define FILE_A_H

/*Your header*/

#endif

In addition to it, you might add a declaration of the class in your main header.

链接地址: http://www.djcxy.com/p/86326.html

上一篇: 避免C程序中的主要(入口点)

下一篇: C ++头文件和编译过程