History Report a problem
Article Edit this page Discussion

Automatic insertion of C/C++ header gates

From Vim Tips Wiki

Jump to: navigation, search
 

Tip 514Previous TipNext Tip

Created: July 21, 2003 Complexity: basic Author: Morten Fjord-Larsen Minimum version: 5.7 Karma: 63/30 Imported from: Tip#514


C/C++ header files should be guarded against multiple inclusions using preprocessor directives, e.g.:

#ifndef FOO_H
#define FOO_H

/* Declarations. */

#endif

Placing the following snippet in your vimrc file, makes Vim insert these preprocessor gates automatically, when a new header file is created:

function! s:insert_gates()
  let gatename = substitute(toupper(expand("%:t")), "\\.", "_", "g")
  execute "normal! i#ifndef " . gatename
  execute "normal! o#define " . gatename . " "
  execute "normal! Go#endif /* " . gatename . " */"
  normal! kk
endfunction
autocmd BufNewFile *.{h,hpp} call <SID>insert_gates()

[edit] Comments

 

 TO DO 
The following is from a proposed new tip that has now been deleted. What is required to make this work? It assumes you start with something?

Here is an alternative, intended to produce:

#ifndef __FILENAME_H
#define __FILENAME_H
#endif //__FILENAME_H

This will add this kind of block at the top of a new .h file at the press of a key. Add to your vimrc file:

nnoremap <F12> "%phr_I#ifndef __<Esc>gUwyypldwidefine <Esc>yypldwiendif //<Esc>O<Esc>

Rate this article:

Share this article:

Hubs Highlights International Sites Wikia messages
Entertainment
Gaming
Cartoons & Comics
Science Fiction
Hobbies
Sports
See all...
Grand Theft Auto
Doctor Who
Legend of Zelda Wiki
Terminator Wiki
Everquest II Wiki
Mystery Science Theater 3000
German
Spanish
Chinese
Japanese
More...
Wikia is hiring for several open positions
Send this article to a friend
"Automatic insertion of C/C++ header gates"
 
 
Hi!

I thought you'd like this page from Wikia!

http://vim.wikia.com

Come check it out!
Send confirmation