This morning, the difference between # ifndef and # pragma once was solved.
To differentiate # The macro definition difference between ifndef and # pragma once, I specially compiled a small program to test the process as follows:
1. Create two header files, huang1.h and huang2.h, as follows:
// Huang1.h
# Include <iostream. h>
# Ifndef HH
# Define hh100
# Endif
Void fanh ()
{
Cout <HH * 2 <Endl;
}
// Huang2.h
# Pragma once
# Include <iostream. h>
Void fan ()
{
Cout <"good" <Endl;
}
2. Create another CPP file, Huang. cpp, as shown below:
# Include <iostream. h>
# Include "huang1.h"
# Include "huang1.h"
# Include "huang2.h"
# Include "huang2.h"
Void main ()
{
Fan ();
Fanh ();
}
3. Run, with the following error:
------------------ Configuration: eaxm-Win32 debug --------------------
Compiling...
Huang. cpp
D:/VC practice/eaxm/huang1.h (6): Error c2084: function 'void _ cdecl fanh (void) 'already has a body
We can see from the above that the function body is repeatedly called. Because the previous two headers include the huang1.h header file, the red header file is commented out,
# Include <iostream. h>
# Include "huang1.h"
// # Include "huang1.h"
# Include "huang2.h"
# Include "huang2.h"
Void main ()
{
Fan ();
Fanh ();
}
Run again and the result is: Good
200
Press any key to continute
The result is correct.
4. But why is there no problem in the two "huang2.h" events? This illustrates a problem.
# Pragma once is guaranteed by the compiler: the same file will not be contained multiple times. That is to say, after huang2.h is opened for the first time, huang2.h will not be opened for the next time, and will be skipped when "huang2.h" is run for the second time, and huang1.h will be opened multiple times, so you will find that the above error occurs when multiple function bodies are called ..
Reference: http://mxdxm.javaeye.com/blog/592542
Http://www.cppblog.com/szhoftuncun/archive/2007/10/28/35356.html