Wednesday, June 21, 2023

Macros in C

Recently we were developing some source code say for feature X.

As part of the development we have written the header file something like below

#ifndef __2023_06_21_001_H__

#define __2023_06_21_001_H__

#if (CUSTOM_FEATURE_X == CUSTOM_FEATURE_VAL)

#define CUSTOM_FEATURE_X     (1u)

#define CUSTOM_FEATURE_VAL   (1u)

typedef struct

{

    unsigned int val;

}feature_x_t;

#endif

#endif /* __2023_06_21_001_H__ */


In a C source file, we have included the above header file. In C source file, we have declared a variable of type feature_x_t as following:

feature_x_t gl_feature_str;




In addition by mistake we have defined the both macro values inside the the header file itself as shown in snippet. We were wondering how the preprocessor, could find the feature_x_t variable type declaration which is being used in C source file.


After a day, what I understood is, it seems as both were not defined, #if (CUSTOM_FEATURE_X == CUSTOM_FEATURE_VAL), condition is passing, and the C Preprocessor processes the further declarations from the header file. Hence the variable type feature_x_t could be found.