Description # differences between ifndef and # pragma once

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.