Compile-time checks
Some mistakes can be caught before the program ever runs: a record whose layout changed, a build made without a setting it needs. The preprocessor can test these while it reads the source, and stop the build when the answer is wrong.
'' Questions answered while compiling, not while running.
type Header
magic as uint32
size as uint32
end type
'' #assert stops the build when its condition is false: if a field is
'' ever added to Header, this program no longer compiles.
#assert sizeof( Header ) = 8
dim as int32 count = 0
dim as int64 total = 0
'' #if typeof( ) compares two types exactly.
#if typeof( count ) = typeof( int32 )
print "count is an int32"
#endif
#if typeof( total ) <> typeof( count )
print "total is a different type"
#endif
'' #print reports a note while the program compiles.
#print the Header layout is checked
print "Header is"; sizeof( Header ); " bytes"
Output
count is an int32
total is a different type
Header is 8 bytes
While it compiles, the program also reports its #print line:
checks.tiko(23,1): note TKO0315: #print the Header layout is checked
|
23 | #print the Header layout is checked
| ^
#assert condstops the build whencondis false. Change the8to12and the build fails withTKO0604, "#assert condition failed". A record that is written to files is a good place for one: the build stops before a file in the old layout is misread.#if typeof( a ) = typeof( b )compares two types exactly:int32is notint64.#print textreports its text as a note,TKO0315, and the build goes on.
#error stops the build with a message of your own:
'' This program needs a setting chosen when it is built.
#ifndef CONFIG
#error "build with -d CONFIG=1 (development) or -d CONFIG=2 (release)"
#else
print "configuration"; CONFIG
#endif
needconfig.tiko(3,5): error TKO0309: #error: "build with -d CONFIG=1 (development) or -d CONFIG=2 (release)"
|
3 | #error "build with -d CONFIG=1 (development) or -d CONFIG=2 (release)"
| ^
Built with -d CONFIG=2, the same file prints configuration 2. Keep the
code that needs the setting in the #else branch: the compiler reads on past
an #error to report everything it can, so code after the #endif that used
CONFIG would add a second error.
For checks on values while the program runs, see Error Handling.
Activities
- Add a
flags as uint16field toHeaderand read the error. - Write an
#ifthat stops the build with#errorunless__FB_64BIT__is defined.