C++ #ifndef for include files, why is all caps used for the header file?

后端 未结 7 1766
猫巷女王i
猫巷女王i 2021-01-06 12:32

I wonder why the name after the #ifndef directive is always all caps and don\'t seem to match the name of the actual header file? What are the rules surrounding

相关标签:
7条回答
  • 2021-01-06 13:17

    It's completely subjective and there are no enforced rules other than those normally associated with the character set for naming pre-processor macros. It's conventional for macros to be defined in upper case. This tends to help them stand out in source code. A convention I tend to stick to is the strict capitalised version of the filename with the period replaced by an underscore and leading and trailing underscores. So, for a file called DataTableNameMangler.hpp the include guard would look like:

    #ifndef _DATATABLENAMEMANGLER_HPP_
    #define _DATATABLENAMEMANGLER_HPP_
    
    ...
    
    #endif // _DATATABLENAMEMANGLER_HPP_
    

    There's no great reason for this though I strongly recommend for consistency that the name matches the filename exactly. I normally use a little class creator script to generate my initial classes. The following Bash snippet gives an idea:

    #!/bin/bash
    INC_GUARD_NAME="_${1^^*}_HPP_"
    echo "#ifndef $INC_GUARD_NAME"
    echo "#ifndef $INC_GUARD_NAME"
    echo
    echo "class $1 {};"
    echo
    echo "#endif // $INC_GUARD_NAME"
    

    Thus:

    $ ./makeclass.bash DataTableNameMangler
    #ifndef _DATATABLENAMEMANGLER_HPP_
    #ifndef _DATATABLENAMEMANGLER_HPP_
    
    class DataTableNameMangler {};
    
    #endif // _DATATABLENAMEMANGLER_HPP_
    

    This is naturally just a very basic example. Importantly, remember to put the comment before the guard name on the last line. #endif takes no parameters so the macro will be passed on to the C++ compiler which will complain about it if it's not commented.

    0 讨论(0)
提交回复
热议问题