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

后端 未结 9 1266
谎友^
谎友^ 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:26

    It is generally expected that modules of code such as .cpp files are compiled once and linked to in multiple projects, to avoid unnecessary repetitive compilation of logic. For example, g++ -o class.cpp would produce class.o which you could then link from multiple projects to using g++ main.cpp class.o.

    We could use #include as our linker, as you seem to be implying, but that would just be silly when we know how to link properly using our compiler with less keystrokes and less wasteful repetition of compilation, rather than our code with more keystrokes and more wasteful repetition of compilation...

    The header files are still required to be included into each of the multiple projects, however, because this provides the interface for each module. Without these headers the compiler wouldn't know about any of the symbols introduced by the .o files.

    It is important to realise that the header files are what introduce the definitions of symbols for those modules; once that is realised then it makes sense that multiple inclusions could cause redefinitions of symbols (which causes errors), so we use include guards to prevent such redefinitions.

提交回复
热议问题