Simple ways to disable parts of code

后端 未结 14 1156
误落风尘
误落风尘 2021-01-31 08:59

This isn\'t a typical question to solve a specific problem, it\'s rather a brain exercise, but I wonder if anyone has a solution.

In development we often need to disable

14条回答
  •  终归单人心
    2021-01-31 09:10

    Wrapping the code with #if 0 does the trick but then you still need to edit the code to enable/disable it. That's not much better than just using the comment block.

    Note that you can also use a defined preprocessor constant:

    #ifdef ENABLE_TESTS
    // code that you want to run ONLY during tests 
    #endif
    

    Now when building the code, you can selectively define/un-define this constant in your build process - IDE/makefile/build script/command-line - without needing to edit the code:

    $ gcc -DENABLE_TESTS source.c
    

    I've added this answer to counter-balance all of the early #if 0 answers, but this construct from the accepted answer is the best answer to the specific question: /**/ foo(); /*/ bar(); /**/. Please use such comment tricks sparingly.

提交回复
热议问题