在Visual Studio中插入包含保护的快速方法

Fast way to insert include guard in Visual Studio

本文关键字:方法 保护 包含 Visual Studio 插入      更新时间:2023-10-16

我想在Visual Studio 2012中新创建的头文件中自动插入include守卫。是否有用于此目的的预定义代码片段?

编辑:我知道#pragma曾经和它的广泛支持编译器。但是我们的编码风格迫使我使用include保护符

在visual studio 2012中使用组合键

Ctrl+K,Ctrl+S

它允许你用代码片段包围选定的代码,例如:

#if, #ifdef, #ifndef, if, class, do, enum,以及更多

. .或者指定你自己的:http://msdn.microsoft.com/en-us/library/ms165394.aspx

#pragma once ?

但是不,我不知道有什么可以自动为您插入#ifndef

由于您正在标记c++,您应该通过内置向导添加类。向导创建#pragma once指令。这甚至对其他编译器也是可用的:#pragma一次,这样你就不会破坏平台的交叉兼容性。

然而,你可以做的是创建一个像这样的VS宏:
Option Strict Off
Option Explicit Off
Imports System
Public Module HeaderGuard
    Sub InsertHeaderGuard()
        Dim filename As String = DTE.ActiveDocument.Name
        filename = filename.ToUpper().Replace("."c, "_"c)
        DTE.ActiveDocument.Selection.Text = "#ifndef " + filename
        DTE.ActiveDocument.Selection.NewLine()
        DTE.ActiveDocument.Selection.Text = "#define " + filename
        DTE.ActiveDocument.Selection.NewLine(2)
        DTE.ActiveDocument.Selection.Text = "#endif /* " + filename + " */"
        DTE.ActiveDocument.Selection.NewLine()
    End Sub
End Module

如果您有Visual Assist X,您可以删除#pragma once(如果存在),选择其余文本,右键单击Surround with (VA) => #ifdef guard in a header。如果你不喜欢默认设置,你可以在VASSISTX菜单中选择Tools => Edit VA Snippets...

你可以使用像autohotkey这样的工具。下面是一个类似问题的答案。