How to properly name include guards in c++

后端 未结 4 1618
忘掉有多难
忘掉有多难 2021-01-21 08:05

I have 3 header files:

misc.h
MyForm.h
Registration.h

In misc.h file I put

#ifndef MISC_H
#define MISC_H
#endif
4条回答
  •  甜味超标
    2021-01-21 08:39

    How to properly name include guards in c++

    Usual convention is to only use upper case characters. Numbers and underscores are fine too except not as the first character. The include guard must be unique: The name must not be used for anything else in the program.

    The name must not be reserved, so you must not use NULL for example. Also, all names that begin with underscore followed by a capital letter, as well as all names that contain two consecutive underscores are reserved.

    MISC_H is not reserved, but keep in mind that if you have another misc.h in another path, then you cannot use the same include guard. It's usually better to use longer names to uniquely identify the file. Perhaps use some kind of prefix, such as company name, or your own name. Typically _H suffix is used to separate from non-guard macros.

    If you have problems with coming up unique names that aren't reserved, or just feel that it's tedious, then you could use #pragma once instead. Be warned that it isn't standard. I've heard rumours about exotic compilers that don't support it, as well as convoluted build processes where hard linked files didn't get guarded as they should. If you encounter such problems, it's trivial to simply add the header guards afterwards.


    Your other headers appear to lack include guards. If you include them in any header, then there will probably be trouble. It's a good practice to guard all header files.


    do I need to put #endif at the bottom of misc.h?

    Yes. The guard only protects the code that is between the define and endif.

提交回复
热议问题