Simple ways to disable parts of code

后端 未结 14 1139
误落风尘
误落风尘 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:11

    In my code, I like to do this in my main.cpp file:

    #define CRAZY_EXPERIMENT
    
    #ifdef TEST
    #include "Test.h"
    #elif ANOTHER_TEST
    #include "AnotherTest.h"
    #elif CRAZY_EXPERIMENT
    #include "CrazyExperiment.h"
    #else
    
    int main(int argc, int * argv[]){
        runTheProgramLikeNormal();
    }
    
    #endif
    

    The header files you see all contain their own main(). There is only ever one main() function in the program based on what is defined in the first #define there. If the statement is omitted entirely, it defaults to the canonical main() function you see written.

    This makes it easy to write tests for my program that only focus on one or two components by themselves. And the best part is that the test headers are neatly quarantined from my code, so no test code gets left in (or even linked in) by mistake.

提交回复
热议问题