Henri Schomäcker wrote:
Hi folks,
I have a quite big class, which I want to use on UNIX-like systems and on
win32.
Until now, everything is absolutely portable. But now I need to read a
directory and use the os dependent functions.
So need to define and include different libraries and functions for both
OS-types. How can I do this using e.g. compiler #define's that all
compilers understand? And can I do this also inside of a function?
I'm using VC++ 6 on win32. Is there a special define set by the IDE like
e.g. __WIN32 or so that I could use?
With UNIX-like OS I'm using the typical combination of gcc, libtool and
autotools.
It's only the dir-read function so I don't want to write seperate
sourcefiles for both OS types.
Apart from using a third party library (as suggested by Peter in a
previous reply), when writing portable code, try not to litter your code
with conditionals. Code with lots of
#if defined(_MSC_VER)
... win32 stuff ...
#elif defined(unix)
... unix stuff ...
#endif
is very unreadable and difficult to maintain hence prone to error.
The alternative I use is to have a single "os.h" file which contains a
minimal amount of conditional stuff and to use the "#include MACRO"
trick. Within the system dependant headers, define exactly the same
interface but implemented in different files for different systems.
e.g.
in - at_os.h
00132 #if defined(WIN32) || defined(_WIN32)
00133
00134 #define AT_ATOMIC_H "at_win32_atomic.h"
00135
00136 #else
00137
00138 #define AT_ATOMIC_H "at_gx86_atomic.h"
00139
00140 #endif
Then in the "atomic.h" header, simply include AT_ATOMIC_H.
e.g.
in atomic.h
#include AT_ATOMIC_H
(system dependant header)
Do not include "windows.h" or any system header file in portable code
header files (with very few exceptions). If you have to, use the PIMPL
idiom to eliminate dependantcies.
An example is in the Austria library:
- portable header file -
http://austria.sourceforge.net/dox/h...8h-source.html
- win32 header file -
http://austria.sourceforge.net/dox/h...8h-source.html
- gnu x86 header file -
http://austria.sourceforge.net/dox/h...8h-source.html