CLion 2021.1 Help

Header guards

Header guard is a pattern of preprocessor directives that protect your header from being included multiple times. Header guard wraps the entire code content into an #ifndef(#if !defined, or another similar) block:

#ifndef MY_HEADER_H #define MY_HEADER_H //... #endif

Edit the header file templates

By default, header guards are included in the file templates that specify the initial content for new headers. You can edit these templates if, for example, you decide to use #pragma once instead of header guards. For this, go to Settings / Preferences | Editor | File and Code Templates and open the Files tab. Select C Header File or C++ Class Header from the list, and change the template content:

header guard in file template

Notice the literal syntax wrapping #pragma once. For file templates, CLion uses the Apache Velocity language, which requires escaping for the C/C++ preprocessor directives in order to parse them correctly.

    Configure the header guard symbol

    • Header guard symbol (MY_HEADER_H from the example above) should be unique, so it usually relates to the filename. To configure the pattern for header guard symbol, open the Naming Convention tab in Settings / Preferences | Editor | Code Style | C/C++ and specify the template in the Header Guard field:

      header guard field in naming convention settings

    • You can use various predefined variables, for example:

      • ${PROJECT_NAME}- the name of the current project.

      • ${PROJECT_REL_PATH}- the relative target path. For instance, if the project is located in the prj directory, and the target file is prj/src/dir/header.h, then ${PROJECT_REL_PATH} will be equal to src/dir.

      • ${FILE_NAME}- the target filename without extension.

      • ${EXT}- the target file extension.

      • Other variables that you can find in file templates, such as ${USER} or ${DATE}.

      A valid header guard symbol can contain the following characters: upper case 'A-Z' and lower case 'a-z' letters, the underscore sign _, digits (but cannot start with a digit), and the dollar sign $. Note that CLion appends an INC_ prefix to symbols that start with digits, and replaces invalid symbols using the INC_${UUID} pattern.

    • The configured symbol replaces the ${INCLUDE_GUARD} variable in the header templates. CLion will apply the pattern when creating new C/C++ classes and header files. Also, if you rename a class or a file, the header guards matching the currently configured style will be updated with the new name:

      automatic changes in header guard template for file rename

    Last modified: 08 March 2021