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.