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)

johhnry
  • 31
  • 3
  • 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](https://github.com/joaotavora/yasnippet) it's a template system quite easy and useful. Good luck! – Fermin MF Aug 17 '20 at 05:43
  • 1
    Thanks you so much! It's the kind of answer that I was waiting for :) – johhnry Aug 18 '20 at 20:55

1 Answers1

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 */
johhnry
  • 31
  • 3