c++qtqt-creatorinclude-guards

Qt creator include guard pattern


There's a way in Qt-Creator to automatically add a template string while creating a new class?

For instance:

I create the new class Foo. The header file auto-generated is

#ifndef FOO_H
#define FOO_H

class Foo{
};

#endif FOO_H

What I would:

#ifndef SOMETHING_FOO_H
#define SOMETHING_FOO_H

class Foo{
};

#endif SOMETHING_FOO_H

Ideally I would like to customize it based on the project like PROJECTNAME_FOO_H or even better PROJECT_NAMESPACE_FOO_H


Solution

  • I achieved to generate header guards of the form NAMESPACE_NESTEDNAMESPACE_CLASSNAME_H. I couldn't find anything to get the project name, but in my case it was not a problem as my top level namespace is my project name.

    Following the answer of @Alan Birtles, I modified the cpp class wizard. You need to copy the files (file.cpp, file.h, wizard.json) from the QtCreator install directory to your home directory ($HOME/.config/QtProject/qtcreator/templates/wizards on Linux and macOS or %APPDATA%\QtProject\qtcreator\templates\wizards on Windows, according to the doc). Put them in the same subfolders (i.e. wizards/classes/cpp).

    In wizard.json, change the line:

    { "key": "GUARD", "value": "%{JS: Cpp.headerGuard('%{HdrFileName}')}" },
    

    to:

    { "key": "GUARD", "value": "%{JS: Cpp.classToHeaderGuard('%{Class}', '%{JS: Util.suffix('%{HdrFileName}')}')}" },
    

    Note that you can add some static text to your liking:

    { "key": "GUARD", "value": "RANDOM_TEXT_%{JS: Cpp.classToHeaderGuard('%{Class}', '%{JS: Util.suffix('%{HdrFileName}')}')}_INCLUDED" },
    

    The complete files can be found here: https://gist.github.com/juleswh/aeacc89342bc51b19044cf1e04483357

    Hope this helps!


    I used the following ressources, in case it might be usefull: