Disable or enable code by preprocessor

大憨熊 提交于 2019-12-31 00:03:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!