Do you know the difference between #pragma once and #ifndef in C++?

Do you know the difference between #pragma once and #ifndef in C++?

Concept:
Both are to prevent header files from being repeatedly included. If this header file changes, then all the source files that include this file need to be recompiled, even if no content is used

Differences:
(1) #ifndef and #pragma once both occur in the preprocessing stage. The method of #ifndef depends on the macro name cannot be conflicted. This not only ensures that the same file will not be included multiple times, but also that the content is exactly the same Two files cannot be accidentally included at the same time. Of course, the disadvantage is that if the macro names of different header files accidentally "crash".

(2) #ifndef is a C/C++ language feature, and #pragma once is an instruction provided by the compiler, and the same file will not be included multiple times. Note that the "same file" mentioned here refers to one physical file, not two files with the same content. The benefit is that you don't have to think about a macro name anymore, and of course there will be no strange problems caused by macro name collisions. The corresponding disadvantage is that if there are multiple copies of a header file, this method cannot guarantee that they will not be included repeatedly.

(3) #pragma depends on the compiler, so some old compilers do not provide it (for example, before vc6), and #ifndef is very portable.

Additional
tips : C++11 introduced the _Pragma operator
#pragma once and _Pragma ("once") has similar effects,
but the former is a preprocessing instruction, and the latter is an operator, which can be used in some macros.

---------------------------- Welcome everyone to add explanation! ! ! ----------------------------

Guess you like

Origin blog.csdn.net/cckluv/article/details/110631320