Re: Use of #ifndef in header files
On Apr 23, 12:51 pm, Johs <a...@asd.com> wrote:
Each time I make a new .h file in eclipse it starts with this:
#ifndef FUNCS_H_
#define FUNCS_H_
// here goes all the code
#endif /*FUNCS_H_*/
where FUNCS_H_ corresponds to the filename funcs.h. But is it always a
good habit to include these preprocessor lines in each .h file?
It depends. You need some sort of include guard, but such a
simple naming convention runs a great risk of name collision,
e.g. in cases like:
#include "myLib/funcs.h"
#include "yourLib/funcs.h"
Within a project or a single company, you'll probably want to
extend the convention to include the subsystem name as well:
#ifndef CompanyName_myLib_funcs_h
#define CompanyName_myLib_funcs_h
// ...
#endif
For code meant to be used as a third party library, you'll
likely want to go even further; I use something like:
name=` basename "$filename" `
guard1=${prefix}` basename "$filename" | sed -e 's:[^a-zA-
Z0-9_]:_:g' `
guard2=`date +%Y%m%d%H%M%S`
guard3=`od -tx1 -N 16 /dev/random | head -1 | sed -e 's/
^[0-9]* //' -e 's/ //g' | tr '[a-f]' '[A-F]'`
guard=${guard1}_${guard2}${guard3}
echo
echo "#ifndef $guard"
echo "#define $guard"
echo
echo "#endif"
echo "// Local Variables: --- for emacs"
echo "// mode: c++ --- for emacs"
echo "// tab-width: 8 --- for emacs"
echo "// End: --- for emacs"
echo "// vim: set ts=8 sw=4 filetype=cpp: --- for vim"
to generate such headers myself. (I've deleted the code which
generates the copyright, but of course, that will normally be
inserted automatically as well.)
I'm not familiar with eclipse, but I would imagine that you can
configure its editor to generate something along these lines as
well. (The above is part of a Unix shell script, which I've
configured my editor to execute whenever it opens a .hh file
which doesn't already exist.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34