Why # ifndef # define # endif is added to the C ++ header file? The variable definition is repeated.

Source: Internet
Author: User

We all know that to prevent header files from being # include multiple times, we usually add the above mechanism to the header files, such as temp. h.

# Ifndef _ temp_h

# DEFINE _ temp_h

......

# Endif

In this way, the header file will only be included once in the same compilation unit.

But is this safe?

Once, a friend asked me why another variable definition error occurs in his program.

I have read his code. A header file is written in the following format:

# Ifndef _ a_h

# DEFINE _ a_h

Int I = 10;

Void F ()

{

...

}

# Endif

There is a problem here. His header file is different from ours. Generally, our header file only uses declaration, and the above defines an I variable and F function.

According to my understanding, there are sometimes multiple compilation units in a project. For example, in a Linux environment, we often have several compilation units. o file, which contains multiple compilation units. This header file may be included by several compilation units. When the final output file is compiled, when they are linked to each other, you will find a redefinition.

To this end, you can change the header file:

# Ifndef _ a_h

# DEFINE _ a_h

Extern int I;

Void F ();

# Endif

 

// A. cpp

# Include "a. h"

Int I = 10;

Void F (){...}

After the modification, the compilation is normal.

Because multiple compilation units can have the same declaration, C ++ allows multiple declarations, as long as they do not conflict with each other, but do not allow repeated definitions, it may be because the definition involves the issue of code space allocation, the Declaration just tells you what kind of things.

Related Article

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.