Wikia

Vim Tips Wiki

Automatic insertion of C/C++ header gates

Talk0
1,612pages on
this wiki
Revision as of 16:35, October 18, 2009 by 64.46.39.215 (Talk)

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

 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>

This is another alternative, also a mapping, intended to produce more verbosely-commented boilerplate but otherwise similar to the above:

:nnoremap <C-F12> "%phr_g0gUw<Esc>I#ifndef __<Esc>g$yiwo<Esc>pI#  define <Esc>gg<Esc>A /* Guard against multiple
 header inclusion error */<Esc>ggjo<Esc>I#endif /* end if-not-def <Esc>pA */<Esc>2O<Esc>

Produces when run on "Phoohaa.h" (must be in that file's working directory):

#ifndef __PHOOHAA_H /* Guard against multiple header instance error */
#  define __PHOOHAA_H


#endif /* end if-not-def __PHOOHAA_H */

Please note however that using double underscores anywhere in your include guard names is not recommended, and symbols starting with a double underscore including defines are reserved for use by the compiler. So in the above example it is best to use:

#ifndef FILENAME_H
#define FILENAME_H
....

For more information, see: http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier



Around Wikia's network

Random Wiki