Is there a reason to distinguish between .h file and .cpp file?

Asked 2 years ago, Updated 2 years ago, 117 views

Why does C++ use header files and .cpp files separately?

c++ header-files

2022-09-22 22:31

1 Answers

The process of compiling C++ can be divided into two main categories.

First, the source text file is binary object file ().OBJ/.It's compiling with O The second is to link all object files to create an executable binary file.

In the first course,

So if you write symbol defined in the B.CPP file in A.CPP as follows, A.CPP is not compiled because the B.CPP file does not know if it has a symbol.

// A.CPP
void fncA()
{
   fncInB(); // functions defined in B.CPP
}

/********** file classification**********/

// // B.CPP
void fncInB()
{
   // Which chord?
}

To resolve this issue, you must declare the corresponding symbol in A.CPP.

// A.CPP
void fncInB(); // declaration of fncInB() in B.CPP

/********** file classification**********/

void fncA()
{
   fncInB(); // defined in B.CPP
}

How do I write fncInB() in C.CPP? Similarly, you can declare fncInB() to C.CPP.

If all 10 different CPP files use fncInB(), should we declare it 10 times in total once in 10 CPP files? fncInB1(), fncInB2(), fncInB3(), ... What should we do if we have more functions together?

It's hard to maintain/repair these cords In the header file, fncInB1(), fncInB2(), and fncInB3() are declared once Use the method to include header files from each CPP file.

When the compiler processes the include, the contents of the file go into that location instead The programmer doesn't copy-paste it himself It's to replace the compiler.

// B.HPP - Header File
void fncInB(); //declare function

/********** file classification**********/

// // A.CPP
#include "B.HPP"

void fncA()
{
   function defined in fncInB(); // B.CPP
}

/********** file classification**********/

// // B.CPP
#include "B.HPP"

void fncInB()
{
   // Which chord?
}

/********** file classification**********/

// // C.CPP
#include "B.HPP"

void fncC()
{
   function defined in fncInB(); // B.CPP
}


2022-09-22 22:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.