Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

后端 未结 9 1280
谎友^
谎友^ 2020-12-02 03:30

I have always seen people write

class.h

#ifndef CLASS_H
#define CLASS_H

//blah blah blah

#endif

The question is, why don\'t they

9条回答
  •  爱一瞬间的悲伤
    2020-12-02 04:31

    It doesn't - at least during the compilation phase.

    The translation of a c++ program from source code to machine code is performed in three phases:

    1. Preprocessing - The Preprocessor parses all source code for lines beginning with # and executes the directives. In your case, the contents of your file class.h is inserted in place of the line #include "class.h. Since you might be includein your header file in several places, the #ifndef clauses avoid duplicate declaration-errors, since the preprocessor directive is undefined only the first time the header file is included.
    2. Compilation - The Compiler does now translate all preprocessed source code files to binary object files.
    3. Linking - The Linker links (hence the name) together the object files. A reference to your class or one of its methods (which should be declared in class.h and defined in class.cpp) is resolved to the respective offset in one of the object files. I write 'one of your object files' since your class does not need to be defined in a file named class.cpp, it might be in a library which is linked to your project.

    In summary, the declarations can be shared through a header file, while the mapping of declarations to definitions is done by the linker.

提交回复
热议问题