The next pattern is common in C code:
#ifndef SOMETHING
#define SOMETHING
#endif
The pattern is possible in Delphi code too:
{$IFNDEF SOMETHING}
{$DEFINE SOMETHING}
{$ENDIF}
but it is not common - I have never seen it at all. If a Delphi code requires a conditional define, it just defines it without IFNDEF
check.
Why so? What is the difference in conditional compilation between C and Delphi so that ifndef
check is needed for former and not needed for latter?
That's because this is not only common but mandatory in C:
While this is rarely used in Delphi. And when used, it's actually used to set up those
{$DEFINE}
's:This matters because DEFINES are only valid while compiling one object (may it be a
.PAS
file or a.C
file). Delphi uses theuses
clause to include other units, while C uses theinclude
to include it's headers. InC
headers might themselves include other headers. The pattern you're asking about is used to prevent recursively re-including the same header.To make maters crystal-clear, here's a sample of what one might use in C, and the equivalent in Delphi. Let's say we've got a 3 files setup, where
A
needs to include bothB
andC
, andB
only needs to includeC
. The "C" files would look like this:Without the conditional defines in
C.h
, theC.h
file would end up being included twice inA.h
. This is how the code would look like in Delphi:The Delphi/Pascal version doesn't need to protect "C" from being included twice in "A" because it doesn't use the
{$INCLUDE}
to achieve this goal, it use theuses
statement. The compiler would get the exported symbols from theB.dcu
file and theC.dcu
files with no risk of including symbols fromC.dcu
twice.Other reasons to see a lot more precompiler directives in C code:
{$DEFINE}
in Delphi code only deals with conditional compilation, while the C variant can be used for both conditional compilation and as a form of word substitution.#include
for headers means you can have a header that defines macros. Or you can have a header that's configured by specifying some#define
statements before the actual#include <header.h>