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

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

    That's done for header files so that the contents only appear once in each preprocessed source file, even if it's included more than once (usually because it's included from other header files). The first time it's included, the symbol CLASS_H (known as an include guard) hasn't been defined yet, so all the contents of the file are included. Doing this defines the symbol, so if it's included again, the contents of the file (inside the #ifndef/#endif block) are skipped.

    There's no need to do this for the source file itself since (normally) that's not included by any other files.

    For your last question, class.h should contain the definition of the class, and declarations of all its members, associated functions, and whatever else, so that any file that includes it has enough information to use the class. The implementations of the functions can go in a separate source file; you only need the declarations to call them.

提交回复
热议问题