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.

Friday, February 17, 2023

CFLAGS with -Wall or -Werror in Modux Toolbox 3.0

In this post we will discuss about CFLAGS with -Wall and -Werror option in Modus Toolbox 3.0 (MTB3.0).

The user need to integrate few C source and header files. Let us assume that the filenames are source_1.c, source_2.c, source_1.h and source_2.h.

To integrate the source files into the MTB3.0 project the files were copied to the existing folder and MTB IDE could include the source files to the project automatically.

The project also contains MTB Shared library which will be generated while creating the project.

Now let us assume a function named my_function defined in source_1.c.

The user calls my_function from one of the source file present inside the mtb_shared folder. However the prototype for the function is not included into the source file which is available in mtb_shared.

As the Makefile contains CFLAGS with -Werror, the compiler stops generating the final output such as hex or bin files.

When we have added the prototype for my_function in the source file present in mtb_shared, then the IDE could generate the hex or bin files. 

The possible solutions to it are, 

  1. To change the CFLAGS Setting from -Werror to -Wall.
  2. Include the prototype for the functions into source files present in mtb_shared.
As removing -Werror might stop generating some other errors such as overflow calculations for example.

Hence it is advised to include the function prototypes.