Search code examples
regexvisual-studio-codereplacemultiline

How to replace all include guards by #pragma once in whole repository in VSCode?


In our project, we use include guards like:

..
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
..
#endif  // #ifndef _SINGLETON_H_
..

The last line can be without comment etc. so the files match something like:
^.*#ifndef\s+[A-Z_]+\s+#define\s+[A-Z_]+(.*\n)*.*#endif.*$.

I want to replace it with:

..
#pragma once
..
..

using Replace All functionality.

How to achieve that?
Probably somehow match the include guard with content, store the content within the include guard, prefix the content with pragma and replace the include guard with content, right?
I am struggling with storing (or not modifying) the content within include guard.


Solution

  • So I made it work myself (at least for our project with 4687 headers replaced):

    1. Search: ^#ifndef\s+[A-Z_].*\s*#define\s+[A-Z_].*((.*\n)+.*)#endif.*$
      Replace: #pragma once$1
    2. Hit Replace All.