Vim Tips Wiki
m (fix typo)
(Merge in new tip, reworded)
Line 35: Line 35:
   
 
==Comments==
 
==Comments==
  +
'''''TODO''''' 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?
See also [[Automatically_add_ifndef_..._to_a_C_header_file]].
 
  +
  +
Here is an alternative, intended to produce:
  +
<pre>
  +
#ifndef __FILENAME_H
  +
#define __FILENAME_H
  +
#endif //__FILENAME_H
  +
</pre>
  +
  +
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:
  +
  +
<pre>
  +
nnoremap <F12> "%phr_I#ifndef __<Esc>gUwyypldwidefine <Esc>yypldwiendif //<Esc>O<Esc>
  +
</pre>
   
 
----
 
----

Revision as of 01:52, 14 February 2008

Tip 514 Printable Monobook Previous Next

created July 21, 2003 · complexity basic · author Morten Fjord-Larsen · version 5.7


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()

Comments

TODO 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>