C ++ header file redefinition Solution

Source: Internet
Author: User

I recently used a lot of header files compiled by myself during development, which makes it easy to see error LNK2005. After reading the materials, I found that many materials on the Internet are reprinted in the same place, at that time, I had to pay a weekly discount on some areas I didn't understand, but finally solved the problem.

There are also a variety of solutions on the Internet. Here is a feasible solution. The development environment is VS 2008.

First, make sure that only variables and functions are declared in the header file. do not define them. This is very important, otherwise there will be problems during the connection. Not only are variables not defined, but do not define functions, but declarations can be made.

Second, if there is an error LNK2005 after the preceding problem is solved, modify the following in each header file:

1. Add at the beginning of the header file

# Ifndef _ HEAD_H _ // if this macro is not defined
# Define _ HEAD_H _ // define this macro

2. Add at the end of the header file

# Endif

The content of the added header file is:

# Ifndef _ HEAD_H _ // if this macro is not defined
# Define _ HEAD_H _ // define this macro

..... // The original content of the header file


# Endif

Note: The purpose of adding the above information is to tell the link program that the header file can be linked only once, so that the problem of redefinition can be avoided. For macro names (here _ HEAD_H _), make sure the names in all header files are different. Otherwise, after the link program defines a header file with the same name, all header files containing the same macro name will not be linked. A common naming method is to put all the headers in uppercase, add _ before and after, and replace with _. If the header file is title. h, name it _ TITIE_H _

After these two steps, the basic error LNK 2005 is solved.

It is for beginners only. If you have any questions, please leave a message.


 

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.