C macro to enable and disable code features

前端 未结 6 1671
Happy的楠姐
Happy的楠姐 2021-01-07 09:44

I\'ve used a code base before that had a macro system for enabling and disabling sections of code. It looked something like the following:

#define IN_USE            


        
6条回答
  •  旧巷少年郎
    2021-01-07 10:23

    The following works. It will give you compile error for FEATURE_D. If you comment out the code for FEATURE_D, then it will execute code for FEATURE_A and FEATURE_B. The code is pretty much self-explanatory. Instead of checking whether FEATURE_D or others are defined inside DoFeatures function, you can just put them inside an if block. In that way, the compiler will try to execute the code block. If it is 1, then the code inside if block will get executed; in case of 0, it will not get executed. And if it is never defined, then will get a compile error.

    #include 
    
    #define IN_USE      1
    #define NOT_IN_USE  0
    
    #define FEATURE_A       IN_USE
    #define FEATURE_B       IN_USE
    #define FEATURE_C       NOT_IN_USE
    
    
    void DoFeatures()
    {
        if(FEATURE_A){
            // Feature A code...
            printf("Feature A\n");
        }
    
        if(FEATURE_B){
            // Feature B code...
            printf("Feature B\n");
        }
    
        if(FEATURE_C){
            // Feature C code...
            printf("Feature C\n");
        }
    
        if(FEATURE_D) {// Compile error since FEATURE_D was never defined
            // Feature D code...
            printf("Feature D\n");
        }
    }
    
    int main(int argc, char **argv)
    {
        DoFeatures();
        return 0;
    }
    

提交回复
热议问题