<font face="Arial, Lucida Sans, Helvetica">
-<table width=100% border=4 cellpadding=5 cellspacing=0>
+<table width=100% border=0 cellpadding=5 cellspacing=0>
<tr>
-<td bgcolor="#660000">
-<font size=+1 face="Arial, Lucida Sans, Helvetica" color="#FFFFFF">
+<td bgcolor="#C4ECF9">
+<font size=+1 face="Arial, Lucida Sans, Helvetica" color="#000000">
wxWindows Programmer Style Guide
</font>
</td>
by <A HREF=mailto:zeitlin@dptmaths.ens-cachan.fr>Vadim Zeitlin</A><P>
This guide is intended for people who are (or intending to start) writing code
-for <A HREF="http://web.ukonline.co.uk/julian.smart/wxwin/" target=_top>wxWindows</A> class library.
+for <A HREF="http://www.wxwindows.org" target=_top>wxWindows</A> class library.
<P>
The guide is separated into two parts: the first one addresses the general
its goal it to make wxWindows as uniform as possible without imposing too
many restrictions on the programmer.
<P>
-Acknowledgements: This guide is partly based on <A
-HREF=http://www.mozilla.org/docs/tplist/catBuild/portable-cpp.html target=_top>
+Acknowledgements: This guide is partly based on <A
+HREF="http://www.mozilla.org/hacking/portable-cpp.html" target=_top>
C++ portability guide</A> by David Williams.
<P>
<LI><A HREF="#no_stl">Don't use STL</A></LI>
<LI><A HREF="#no_fordecl">Don't declare variables inside <TT>for()</TT></A></LI>
<LI><A HREF="#no_nestedclasses">Don't use nested classes</A></LI>
+ <LI><A HREF="#no_newlogicalops">Don't use new logical operators keywords</A></LI>
+ </OL>
+ <BR>
+ <LI>Other compiler limitations</LI>
+ <OL>
+ <LI><A HREF="#no_ternarywithobjects">Use ternary operator ?: carefully</A></LI>
+ <LI><A HREF="#no_autoaggregate">Don't use initializers with automatic arrays</A></LI>
+ <LI><A HREF="#no_dtorswithoutctor">Always have at least one constructor in a class with destructor</A></LI>
</OL>
<BR>
<LI>General recommendations</LI>
<OL>
+ <LI><A HREF="#no_cppcommentsinc">No C++ comments in C code></A></LI>
<LI><A HREF="#no_globals">No global variables with constructor</A></LI>
<LI><A HREF="#no_warnings">Turn on all warnings and eradicate them</A></LI>
<LI><A HREF="#no_assume_sizeof">Don't rely on <TT>sizeof(int) == 2</TT>...</A></LI>
<LI><A HREF="#no_assignment_in_if">No assignments in conditional expressions</A></LI>
- <LI><A HREF="#no_comment_code">Use <TT>#if 0</TT> rather than comments to temporarily
- disable blocks of code</A></LI>
+ <LI><A HREF="#no_comment_code">Use <TT>#if 0</TT> rather than comments to temporarily disable blocks of code</A></LI>
+ <LI><A HREF="#no_overloaded_virtuals">Avoid overloaded virtual functions</A></LI>
<LI><A HREF="#no_extra_semicolon">Don't use extra semi-colons on top level</A></LI>
</OL>
<BR>
<LI><A HREF="#no_carriagereturn">Avoid carriage returns in cross-platform code</A></LI>
<LI><A HREF="#no_caps_in_filenames">Use only lower letter filenames</A></LI>
<LI><A HREF="#no_incomplete_files">Terminate the files with a new-line</A></LI>
+ <LI><A HREF="#no_case_only_diff">Avoid globals differing by case only</A></LI>
</OL>
<BR>
<LI>Style choices</LI>
<OL>
<LI><A HREF="#naming_conv">Naming conventions: use <TT>m_</TT> for members</A></LI>
- <LI><A HREF="#no_void_param">Don't use <TT>void</TT> for functions without
- arguments</A></LI>
- <LI><A HREF="#no_const_int">Don't use <TT>const</TT> for non pointer/reference
- arguments</A></LI>
+ <LI><A HREF="#no_void_param">Don't use <TT>void</TT> for functions without arguments</A></LI>
+ <LI><A HREF="#no_const_int">Don't use <TT>const</TT> for non pointer/reference arguments</A></LI>
</OL>
</UL>
<LI><A HREF="#indentation">Indent your code with 4 spaces (no tabs!)</A></LI>
<LI><A HREF="#class_decl">Order of parts in a class declarations</A></LI>
</OL>
-
+
<BR>
<LI>More about naming conventions</LI>
<OL>
<LI><A HREF="#wx_prefix">Use wx or WX prefix for all public symbols</A></LI>
- <LI><A HREF="#wxdllexport">Use WXDLLEXPORT with all classes/functions in
- wxMSW/common code</A></LI>
+ <LI><A HREF="#wxdllexport">Use WXDLLEXPORT with all classes/functions in wxMSW/common code</A></LI>
<LI><A HREF="#set_get">Use Set/Get prefixes for accessors</A></LI>
+ <LI><A HREF="#constants">wxNAMING_CONSTANTS</A></LI>
</OL>
<BR>
<H3>General C++ Rules</H3>
<UL>
<LI>New or not widely supported C++ features</LI>
-
+
<P>The usage of all features in this section is not recommended for one reason: they appeared in C++ relatively recently and are not yet
supported by all compilers. Moreover, when they're supported, there are
differences between different vendor's implementations. It's understandable that
<P>Just to suppress any doubts that there are compilers which don't support
these new features, you can think about Win16 (a.k.a. Win 3.1) compilers,
<I>none</I> of which supports <I>any</I> feature from the list below.
-
+
<OL>
<P><LI><A NAME="no_templates"></A><B>Don't use C++ templates</B></LI><P>
Besides the reasons mentioned above, template usage also makes the
any type without compromising C++ type system, i.e. using <TT>void *</TT>
is out of question). wxWindows provides <A HREF="TODO">dynamic
arrays and lists</A> which are sufficient in 99% of cases - please don't hesitate
-to use them. Lack of template is not a reason to use static arrays or
+to use them. Lack of template is not a reason to use static arrays or
type-less (passing by <TT>void *</TT>) containers.
<P><LI><A NAME="no_exceptions"></A><B>Don't use C++ exceptions</B></LI><P>
void ReadAddressBookFile(const wxString& strName)
{
wxFile file;
-
+
if ( !file.Open(strFile) )
return;
-
+
...process it...
}
</PRE>
bool ReadAddressBookFile(const wxString& strName)
{
wxFile file;
-
+
if ( !file.Open(strFile) ) {
// wxFile logged an error because file couldn't be opened which
// contains the system error code, however it doesn't know what
// this file is for and an error message "can't open $GLCW.ADB"
// can be quite confusing for the user. Here we say what we mean.
- wxLogError("Can't read address book from '%s'!",
+ wxLogError("Can't read address book from '%s'!",
strName.c_str());
return false;
}
-
+
...process it...
-
+
return true;
}
</PRE>
bool ReadAddressBookFile(const wxString& strName)
{
wxFile file;
-
+
// start a block inside which all log messages are suppressed
{
wxLogNull noLog;
if ( !file.Open(strFile) )
return false;
}
-
+
...process it...
-
+
return true;
}
</PRE></LI>
</UL>
</OL>
-
+
<P><LI><A NAME="no_rtti"></A><B>Don't use RTTI</B></LI><P>
RTTI stands for Run-Time Type Information and there is probably no other
reason not to use it except the portability issue and the fact that it adds
in the implementations I'm aware of).
<P><U>Workaround</U>: use wxWindows RTTI system which allows you to do almost
everything which the new C++ RTTI, except that, of course, you have to use
-macros instead of the (horrible looking, BTW) <TT>dynamic_cast</TT>.
+macros instead of the (horrible looking, BTW) <TT>dynamic_cast</TT>.
<P><LI><A NAME="no_namespaces"></A><B>Don't use namespaces</B></LI><P>
This topic is subject to change with time, however for the moment all wxWindows
years ago, however many compilers still will complain about second declaration
of <TT>i</TT> in the following code:
<PRE>
- for ( int i = 0; i < 10; i++ ) {
+ for ( int i = 0; i < 10; i++ ) {
...
}
...
- for ( int i = 0; i < 10; i++ ) {
+ for ( int i = 0; i < 10; i++ ) {
...
}
</PRE>
-Even if it's perfectly legal now.
+even though if it's perfectly legal now.
<P><U>Workaround</U>: write this instead:
<PRE>
int i;
- for ( i = 0; i < 10; i++ ) {
+ for ( i = 0; i < 10; i++ ) {
...
}
...
- for ( i = 0; i < 10; i++ ) {
+ for ( i = 0; i < 10; i++ ) {
...
}
</PRE>
+or, even better, use different names for the variables in the different for
+loops (in particular, avoid mute variable names like <tt>i<tt> above) - then
+you can declare them in the loop statement and don't pollute the outer name
+space with local loop variables.
<P><LI><A NAME="no_nestedclasses"></A><B>Don't use nested classes</B></LI><P>
Nested classes are, without doubt, a very good thing because they allow to hide
private:
class PrivateLibClass *m_pObject;
};
-
+
// in the .cpp file
class PrivateLibClass { ... };
-
+
PublicLibClass::PublicLibClass()
{
m_pObject = new PrivateLibClass;
-
+
...
}
-
+
PublicLibClass::~PublicLibClass()
{
delete m_pObject;
<P>A nice side effect is that you don't need to recompile all the files
including the header if you change the PrivateLibClass declaration (it's
an example of a more general interface/implementation separation idea).
+
+<P><LI><A NAME="no_newlogicalops"></A><B>Don't use new logical operators keywords</B></LI><P>
+The C++ standard has introduced the following new reserved words: <tt>or</tt>,
+<tt>and</tt>, <tt>not</tt>, <tt>xor</tt>, <tt>bitand</tt>, <tt>bitor</tt>,
+<tt>compl</tt>, <tt>and_eq</tt>, <tt>or_eq</tt>, <tt>not_eq</tt>,
+<tt>or_eq</tt> which can be used instead of the usual C operations &&,
+||, ~ etc.
+<P>This wonderful (and not backwards compatible in addition to being
+absolutely useless) new feature means that these new keywords should not be
+used as the variable names - even if current compilers usually will accept
+this, your code will break in the future. For most of the keywords, using them
+as variable names is quite unlikely, but <tt>or</tt> and <tt>compl</tt> were
+used in the wxWindows sources which seems to indicate that they are the most
+likely candidates.
+<P>It goes without saying that these new keywords should not be used instead
+of the tradional C operators neither both because most compilers don't accept
+them and because using them in C code makes it less readable.
+</OL>
+
+ <BR>
+ <LI>Other compiler limitations</LI><P>
+This section lists the less obvious limitations of the current C++ compilers
+which are less restrictive than the ones mentioned in the previous section but
+are may be even more dangerous as a program which compiles perfectly well on
+some platform and seems to use only standard C++ featurs may still fail to
+compile on another platform and/or with another compiler.
+
+<OL>
+ <P><LI><A NAME="no_ternarywithobjects"></A><B>Use ternary operator ?: carefully</B></LI><P>
+ The ternary operator <TT>?:</TT> shouldn't be used with objects (i.e. if any
+of its operands are objects) because some compilers (notably Borland C++) fail
+to compile such code.
+<P><U>Workaround</U>: use <TT>if/else</TT> instead.
+<PRE>
+ wxString s1, s2;
+
+ // Borland C++ won't compile the line below
+ wxString s = s1.Len() < s2.Len() ? s1 : s2;
+
+ // but any C++ compiler will compile this
+ wxString s;
+ if ( s1.Len() < s2.Len() )
+ s = s1;
+ else
+ s = s2;
+</PRE>
+
+ <P><LI><A NAME="no_autoaggregate"></A><B>Don't use initializers with automatic arrays</B></LI><P>
+The initializers for automatic array variables are not supported by some older
+compilers. For example, the following line
+<PRE>
+ int daysInMonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
+</PRE>
+will fail to compile with HP-UX C++ compiler.
+<P><U>Workaround</U>: either make the array static or initialize each item
+separately: in the (stupid) example above, the array should be definitely
+declared as <TT>static const</TT> (assuming that the leap years are dealt with
+elsewhere somehow...) which is ok. When an array is really not const, you
+should initialize each element separately.
+
+ <P><LI><A NAME="no_dtorswithoutctor"></A><B>Always have at least one constructor in a class with destructor</B></LI><P>
+It is a good rule to follow in general, but some compilers (HP-UX) enforce it.
+So even if you are sure that the default constructor for your class is ok but
+it has a destructor, remember to add an empty default constructor to it.
</OL>
<BR>
- <LI>General recommendations</B></LI><P>
+ <LI>General recommendations</LI><P>
While the recommendations in the previous section may not apply to you if you're
only working with perfect compilers which implement the very newest directives of
-C++ standard, this section contains compiler- (and language-) independent advice
+C++ standard, this section contains compiler- (and language-) independent advice
which <B>must</B> be followed if you wish to write correct, i.e. working, programs. It
-also contains some C/C++ specific remarks in the end which are less
+also contains some C/C++ specific remarks in the end which are less
important.
<OL>
+ <P><LI><A NAME="no_cppcommentsinc"><B>No C++ comments in C code></B></LI><P>
+Never use C++ comments in C code - not all C compilers/preprocessors
+understand them. Although we're mainly concerned with C++ here, there are
+several files in wxWindows sources tree which are compiled with C compiler.
+Among them are <TT>include/wx/setup.h</TT> and <TT>include/wx/expr.h</TT>.
+
+Another thing related to C vs C++ preprocessor differences is that some old C
+preprocessors require that all directives start in the first column (while
+it's generally allowed to have any amount of whitespace before them in C++),
+so you should start them in the beginning of the line in files which are
+compiled with C compiler.
+
<P><LI><A NAME="no_globals"></A><B>No global variables with constructors</B></LI><P>
In C++, the constructors of global variables are called before the
-<TT>main()</TT> function (or <TT>WinMain()</TT> or any other program entry point)
+<TT>main()</TT> function (or <TT>WinMain()</TT> or any other program entry point)
starts executing. Thus, there is no possibility to initialize <I>anything</I>
before the constructor call. The order of construction is largely
implementation-defined, meaning that there is no guarantee that one global
Although close to the heart of many C programmers (I plead guilty), code like
classical <TT>if ( (c = getchar()) != EOF )</TT> is bad because it prevents you
from enabling "assignment in conditional expression" warning (see also
-<A HREF="#no_warnings">above</A>) warning which is helpful to detect common
+<A HREF="#no_warnings">above</A>) which is helpful to detect common
mistypes like <TT>if ( x = 2 )</TT> instead of <TT>if ( x == 2 )</TT>.
<P><LI><A NAME="no_comment_code"></A><B>Use <TT>#if 0</TT> rather than comments to temporarily
The reason is simple: if there are any <TT>/* ... */</TT> comments inside
<TT>...</TT> the second version will, of course, miserably fail.
+ <P><LI><A NAME="no_overloaded_virtuals"></A><B>Avoid overloaded virtual functions</B></LI><P>
+
+You should avoid having overloaded virtual methods in a base class because if
+any of them is overriden in a derived class, then all others must be overriden
+as well or it would be impossible to call them on an object of derived class.
+
+For example, the following code:
+
+<PRE>
+ class Base
+ {
+ public:
+ virtual void Read(wxFile& file);
+ virtual void Read(const wxString& filename);
+ };
+
+ class Derived : public Base
+ {
+ public:
+ virtual void Read(wxFile& file) { ... }
+ };
+
+ ...
+
+ Derived d;
+ d.Read("some_filename"); // compile error here!
+</PRE>
+
+will fail to compile because the base class function taking <TT>filename</TT>
+is hidden by the virtual function overriden in the derived class (this is
+known as [virtual] function name hiding problem in C++).
+
+<P>
+The standard solution to this problem in wxWindows (where we have such
+situations quite often) is to make both <TT>Read()</TT> functions not virtual
+and introduce a single virtual function <TT>DoRead()</TT>. Usually, it makes
+sense because the function taking a filename is (again, usually) implemented
+in terms of the function reading from a file anyhow (but making only this
+functions not virtual won't solve the above problem!).
+<P>
+So, the above declarations should be written as:
+<PRE>
+ class Base
+ {
+ public:
+ void Read(wxFile& file);
+ void Read(const wxString& filename);
+
+ protected:
+ virtual void DoRead(wxFile& file);
+ };
+
+ class Derived : public Base
+ {
+ protected:
+ virtual void DoRead(wxFile& file) { ... }
+ };
+</PRE>
+
+This technique is widely used in many of wxWindows classes - for example,
+<TT>wxWindow</TT> has more than a dozen of <TT>DoXXX()</TT> functions which
+allows to have many overloaded versions of commonly used methods such as
+<TT>SetSize()</TT>
+
<P><LI><A NAME="no_extra_semicolon"></A><B>Don't use extra semi-colons on top level</B></LI><P>
Some compilers don't pay any attention to extra semicolons on top level, as in
<PRE>
</OL>
<BR>
- <LI>Unix/DOS differences</B></LI><P>
+ <LI>Unix/DOS differences</LI><P>
Two operating systems supported by wxWindows right now are (different flavours
of) Unix and Windows 3.1/95/NT (although Mac, OS/2 and other ports exist/are
being developed as well). The main differences between them are summarized
like files without terminating new-line. Such files also give a warning message
when loaded to vim (the Unix programmer's editor of choice :-)), so please think
about terminating the last line.
+
+ <P><LI><A NAME="no_case_only_diff"></A><B>Avoid globals differing by case only</B></LI><P>
+The linker on VMS is case-insensitive. Therefore all external variables and
+functions which differ only in case are not recognized by the linker as
+different, so all externals should differ in more than the case only:
+i.e. <TT>GetId</TT> is the same as <TT>GetID</TT>.
+
</OL>
-
+
<BR>
- <LI>Style choices</B></LI><P>
- All wxWindows specific style guidelines are specified in the next
+ <LI>Style choices</LI><P>
+ All wxWindows specific style guidelines are specified in the next
section, here are the choices which are not completely arbitrary,
but have some deeper and not wxWindows-specific meaning.
<OL>
<P><LI><A NAME="naming_conv"></A><B>Naming conventions: use <TT>m_</TT> for members</B></LI><P>
-It's extremely important to write readable code. One of the first steps in this
-direction is the choice of naming convention. It may be quite vague or strictly
-define the names of all the variables and function in the program, however it
-surely must somehow allow the reader to distinguish between variable and
-functions and local variables and member variables from the first glance.
+We all know how important it is to write readable code. One of the first steps
+in this direction is the choice of naming convention. It may be quite vague or
+strictly define the names of all the variables and function in the program,
+however it surely must somehow allow the reader to distinguish between
+variable and functions and local variables and member variables from the first
+glance.
<P>The first requirement is commonly respected, but for some strange reasons, the
second isn't, even if it's much more important because, after all, the immediate
context usually allows you to distinguish a variable from a function in
void Foo::Bar(int x_)
{
...
-
+
x = x_;
-
+
...
}
</PRE>
and even cannot be removed if <TT>Foo()</TT> is virtual and overridden (because
the names are mangled differently). So, <I>for arguments passed by value</I>
you shouldn't use <TT>const</TT>.
-<P>Of course, it doesn't apply to functions such as
+<P>Of course, it doesn't apply to functions such as
<TT>void PrintMessage(const char *text)</TT> where <TT>const</TT> is mandatory.
</OL>
</UL>
in "include" and "src". So, for example, there is "src/msw", "include/gtk"
etc. There are also two special subdirectories called "common" and
"generic". The common subdirectory contains the files which are platform
-independent (wxObject, wxString, ...) and the generic one the generic
+independent (wxObject, wxString, ...) and the generic one the generic
implementations of GUI widgets, i.e. those which use only other wxWindows
classes to implement them. For the platforms where the given functionality
cannot be implemented natively, the generic implementation is used and the native
setup as well to allow including <TT><wx/foo.h></TT> on any platform.<P>
Note that wxWindows implementation files should use quotes when including wxWindows
-headers, not angled brackets. Applications should use angled brackets. There
-is a reason for it (can anyone remember what this is?).
+headers, not angled brackets. Applications should use angled brackets. This
+ensures that the dependencies are correctly handled by the compiler.
<P><LI><A NAME="include_guards"></LI><B>Include guards</B><P>
To minimize the compile time C++ programmers often use so called include
<P><LI><A NAME="indentation"></LI><B>Indent your code with 4 spaces (no tabs!)</B>
<P><LI><A NAME="class_decl"></LI><B>Order of parts in a class declarations</B><P>
</OL>
-
+
<P><LI>More about naming conventions</LI><P>
<OL>
<P><LI><A NAME="wx_prefix"></LI><B>Use wx or WX prefix for all public symbols</B>.
wx should be used for functions and classes, WX for macros.
- <P><LI><A NAME="wxdllexport"</LI><B>Use WXDLLEXPORT with all classes/functions in
+ <P><LI><A NAME="wxdllexport"</LI><B>Use WXDLLEXPORT with all classes/functions in
wxMSW/common code</B>
The title says it all - every public (in the sense that it is not internal to
the library) function or class should have WXDLLEXPORT macro in its
The reason for the strange syntax for data is that some compilers use different
keyword ordering for exporting data.
-<P>There also several other places where you should take care of shared
-library case: all IMPLEMENT_xxx macros which are usually used in the
-corresponding .cpp files must be taken inside
-"<TT>#if !USE_SHARED_LIBRARY</TT>" and in the <TT>#if USE_SHARED_LIBRARY</TT>
-case you should put them inside <TT>common/cmndata.cpp</TT> file.
-
<P><LI><A NAME="set_get"></LI><B>Use Set/Get prefixes for accessors</B><P>
-There is a convention in wxWindows to prefix the accessors (i.e. any simple, in
-general, inline function which does nothing else except changing or returning
+There is a convention in wxWindows to prefix the accessors (i.e. any simple, in
+general, inline function which does nothing else except changing or returning
the value of a member variable) with either <TT>Set</TT> or <TT>Get</TT>.
+
+ <P><LI><A NAME="constants"></LI><B>wxNAMING_CONSTANTS</B><P>
+The constants in wxWindows code should be defined using <TT>enum</TT> C++
+keyword (and not with <TT>#define</TT> or <TT>static const int</TT>). They
+should be declared in the global scope (and not inside class declaration) and
+their names should start with a <TT>wx</TT> prefix. Finally, the constants
+should be in all capital letters (except the first 2) to make it easier to
+distinguish them from the variables with underscores separating the words.
+
+<P>For example, file-related constants should be declared like this:
+<pre>
+enum
+{
+ wxFILEOPEN_READ,
+ wxFILEOPEN_WRITE,
+ wxFILEOPEN_READWRITE
+};
+</pre>
+
</OL>
<P><LI>Miscellaneous</LI><P>
instead of including the header of corresponding class is better because not
only does it minimize the compile time, it also simplifies the dependencies
between different source files.
-<P>On a related subject, in general, you should try not to include other
+<P>On a related subject, in general, you should try not to include other
headers from a header file.
<P><LI><A NAME="debug_macros"></LI><B>Use debugging macros</B><P>
values - otherwise, a person using a not implemented function has no idea that
it is, in fact, not implemented.
<P>As all debugging macros only do something useful if the symbol
-<TT>__DEBUG__</TT> is defined, you should compile your programs in debug mode to profit
+<TT>__WXDEBUG__</TT> is defined, you should compile your programs in debug mode to profit
from them.
</OL>
</UL>