C++ header files are compiled repeatedly

Repeated compilation means repeated execution of a certain .h file

details as following:

The following are test1.h and test2.h; test1.h is included in test2.h

Below is main.cpp, which contains the above .h file


When running, we run test1.h first and then test2.h until main.cpp runs, but test1.h is included in test2.h. So there will be repeated definitions of test1.h. So it will report an error


Solution

The first:

     Add #pragma once to the front of the test1.h code

     At this time, when test1.h is called for the second time, it will be judged that the time has been called, so as to avoid errors.

     But this method only applies to Microsoft's compiler, so it is not widely applicable.

The second type:

    Change the program to

#ifndef TEST1_H_
#define TEST1_H_
。。。。。。
#endif

Let's look at the meaning of these lines of code:

First, ifndef is if not define: it means that if it is not defined, execute the following define definition + the following code

Otherwise end

In this way, the error of repeated compilation of files is also realized.

So when writing code, it is best to add these three sentences after the file is created, and then write the code to prevent errors.

Guess you like

Origin blog.csdn.net/qq_46423166/article/details/112408160