Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable or enable code by preprocessor

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?

like image 658
marmistrz Avatar asked Mar 14 '23 02:03

marmistrz


2 Answers

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 ...;
like image 192
Martin Jambon Avatar answered Mar 17 '23 07:03

Martin Jambon


you can use cppo : https://github.com/mjambon/cppo. This is available via opam, and offers C like preprocessor features.

like image 20
Pierre G. Avatar answered Mar 17 '23 07:03

Pierre G.