Search code examples
c++compiler-directives

Controlling compiler directive in file from other file C++


Consider following header file,

    // filename : packet_types.h
    #ifndef _PACKET_TYPES_
    #define _PACKET_TYPES_

    struct Packet {
        enum Type {
           typ_ONE,
           typ_TWO, 
           typ_THREE,
        };

        static const char * STRINGS[] = { 
           "ONE",
           "TWO",
           "THREE"
        };

        const char * getText( int enum ) {
             return STRINGS[enum];
        }
    };
    #endif

As Arduino has limited memory, I don't want to include this portion of code when I include this file, packet_types.h,

        static const char * STRINGS[] = { 
           "ONE",
           "TWO",
           "THREE"
        };

        const char * getText( int enum ) {
             return STRINGS[enum];
        }

But for my GUI application, I want the complete file. I want to use same file for both Arduino and GUI, but how can I add compiler directive #define,#ifdef, #ifndef... to do this job, when I include this file from some other file(main.cpp). Thanks.


Solution

  • Although it is possible to use some preprocessor juggling, the right solution is to simply use C++ as it was intended to be used. Only declare these class members and methods in the header file:

        static const char * STRINGS[];
    
        const char * getText( int enum );
    

    And then define them in one of the source files:

        const char * Packet::STRINGS[] = { 
           "ONE",
           "TWO",
           "THREE"
        };
    
        const char * Packet::getText( int enum ) {
             return STRINGS[enum];
        }
    

    With the aforementioned preprocessor juggling, all it ends up accomplishing is the same logical result, but in a more confusing and roundabout way.