问题
In C++ I'd write
bool positive (int a)
{
#ifdef DEBUG
cout << "Checking the number " << a << "\n";
#endif
return a > 0;
}
In OCaml I could write
let positive x =
begin
printf "Checking the number %d\n" x;
x > 0
end
But how can I disable the printf statement when not in debug mode?
回答1:
you can use cppo : https://github.com/mjambon/cppo. This is available via opam, and offers C like preprocessor features.
回答2:
Without preprocessing you can simply have a global flag defined as let debug = true
and write:
if debug then printf ...;
This code is removed by ocamlopt if debug
is false. That said, it's cumbersome and should be used only where performance of the production code is critical.
Another, less optimized, option is to have a mutable flag. This is more convenient as you don't have to rebuild the program to activate or deactivate debug logging. You would use a command-line option to control this (see the documentation for the Arg
module).
let debug = ref false ... if !debug (* i.e. debug's value is true *) then printf ...;
来源:https://stackoverflow.com/questions/33900307/disable-or-enable-code-by-preprocessor