Search code examples
cforward-declaration

Is it possible to forward declare a static const int in the same header?


So same as title: I want to forward declare a integer so I can use it before I define it but the twist is that it needs to happen in the exact same header file.

My code looks like this:

//Embedded system header file for pins and UART.

#if peripheral
#define P4_2 18
#define P4_3 17

static const int AUX_UARTRXD = P4_2;    /* Receive  Data (RXD) at P4.2 */
static const int AUX_UARTTXD = P4_3;    /* Transmit Data (TXD) at P4.3 */

#undef P4_2
#undef P4_3
#endif

static const int P4_2 = 18;
static const int P4_3 = 17;

I really want to have a symbolic way to initialize AUX_UARTRXD but my solution is really ugly.

Moving the declarations is an option but it would mean that the default pattern for the header files would get changed.


Solution

  • What is not optimal in your solution is that you have to define twice the values 17 and 18. It would be a pain in case you have to modify it, introducing a misalignment risk.

    It's not exactly the forward declaration you are asking for, but it could be even a cleaner solution. What if you add two more defines for the values?

    // Outside #if peripheral
    #define P4_2_VAL 18
    #define P4_3_VAL 17
    
    #if peripheral
    static const int AUX_UARTRXD = P4_2_VAL;    /* Receive  Data (RXD) at P4.2 */
    static const int AUX_UARTTXD = P4_3_VAL;    /* Transmit Data (TXD) at P4.3 */
    #endif
    
    static const int P4_2 = P4_2_VAL;
    static const int P4_3 = P4_3_VAL;
    

    In this way you also get rid of those #undefs.