0

I am currently learning C++ and I came across include guards to avoid double inclusion.

Now I would like to use the google's style convention like this :

// project/src/app.hpp

#ifndef PROJECT_SRC_APP_HPP_
#define PROJECT_SRC_APP_HPP_
...
#endif  // PROJECT_SRC_APP_HPP_

and also

// project/src/util/test.hpp

#ifndef PROJECT_SRC_UTIL_TEST_HPP_
#define PROJECT_SRC_UTIL_TEST_HPP_
...
#endif  // PROJECT_SRC_UTIL_TEST_HPP_

So the macro name is basically the path of the header file in the current project.

My goal is to automate this task of writing the include guards each time I create a new .hpp file. I looked at the emacs auto insert mode which looks adapted to the situation but the question is the following :

I am using projectile so how can I get the full path from the root directory of the current project to construct the macro name?

Can anyone point me into the right direction? (btw I am using spacemacs)

2
  • Yes, there is a function called projectile-project-root which tell you the projectile workspace root directory, about the second question seems like for that task you could use yasnippet it's a template system quite easy and useful. Good luck!
    – f-sasa
    Aug 17, 2020 at 5:43
  • 1
    Thanks you so much! It's the kind of answer that I was waiting for :)
    – johhnry
    Aug 18, 2020 at 20:55

1 Answer 1

3

Thanks to f-sasa, I was able to write my own yasnippet file in order to construct the include guard. With the help of this yasnippet example and also this thread about getting the projectile file path :

# key: include_guard
# name: C++ auto header include guard in project
# --

#ifndef ${1:`(upcase
              (concat
               (projectile-project-name)
               "_"
               (subst-char-in-string ?/ ?_
                                     (file-relative-name
                                      (file-name-sans-extension buffer-file-name)
                                      (projectile-project-root)))))`_HPP_}
#define $1

$0

#endif /* $1 */

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.