[Qt-creator] Minimizing compile-time conditionals in Qt Creator

Christian Kandeler christian.kandeler at nokia.com
Tue Aug 28 09:56:14 CEST 2012


[This message is intended for people contributing code to the project. 
If you do not care about development *of* Qt Creator, the following is 
probably not terribly relevant to you.]


Hi,

as you all know, QtCreator is a cross-platform tool, running on Windows 
as well as on several unixoid platforms such as Linux and OS X. While 
most of the time Qt does the necessary abstractions for us, sometimes it 
is necessary to explicitly differentiate between the different host 
platforms. As of now, this differentiation is typically done via 
compile-time conditionals:
     #ifdef Q_OS_WIN
     #include <windows.h>
     #endif
In this example, the #ifdef is unavoidable, because only Windows 
platforms have the windows.h header, so the code would not compile 
otherwise. However, most of the time that is not the case, such as in 
this example:
     QStringList rc(QLatin1String(".svn"));
     #ifdef Q_OS_WIN
         rc.push_back(QLatin1String("_svn"));
     #endif
     return rc;
The code would compile on any platform, but we hide it from the compiler 
and Qt Creator's code model on all of them except Windows. This means 
that if, for instance, you are developing on Linux and you are using 
Creator's refactoring support to rename the rc variable in the above 
example, Creator will miss the occurrence inside the #ifdef'ed block, as 
that one is not part of the code model. Making matters worse, you won't 
even notice the problem during the following compile cycle, because the 
compiler ignores that block of code as well. Assuming you do not have 
access to a Windows machine yourself and your reviewer does not catch 
the mistake, the erroneous code will be checked into the repository and 
annoy the unlucky Windows user who happens to pull from it next. (Note: 
If you are now saying "But why would I use the rename functionality in 
such a short function?", you are missing the point entirely.)
I have therefore added the new utility class HostOsInfo, which enables 
you to write the second example like this:
     QStringList rc(QLatin1String(".svn"));
     if (Utils::HostOsInfo::isWindowsHost())
         rc.push_back(QLatin1String("_svn"));
     return rc;
As you can see, nothing is being hidden anymore from code parsers, 
getting rid of this particular class of problems. I encourage you to use 
this idiom in Creator code whenever possible and only to fall back to 
the Q_OS_* macros when they are unavoidable.


Thanks,
Christian



More information about the Qt-creator mailing list