user2579721
user2579721

Reputation: 89

C - Unusual array initialization

I am working on some legacy C code that has this unusual array initialization:

uint32_t defsMB40000[REG40000_SIZE] = 
{
 #include "modbusDefs40000.h"
}; 

The header file is a list of comma separated numbers and comments. I have never seen this construct before but it does seem to work correctly. Would it not be better to have inside the header:

uint32_t defsMB40000[REG40000_SIZE] = 
{
   0,
   0xFF,
   ...
}; 

and then

 #include "modbusDefs40000.h"

in the .c file?

I suspect the reason it even exists is that the header file is created by a python script. I would appreciate your comments on this idiom and if you have seen the likes of it.

Thanks,

jh

Upvotes: 3

Views: 79

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

This is not an idiom, it's just a trick that gets the job done using the rules of C preprocessor. Essentially, the authors relied on the fact that C preprocessor works as if the content of the file were literally embedded at the point of inclusion. The result is messy, but it accomplishes the task of initializing the array.

Since C headers are expected to have a certain structure, naming the file modbusDefs40000.h is misleading. Using a different extension, e.g. modbusDefs40000.data or something to the same effect, would give readers more clarity as to the purpose of the file.

If you are looking for a way to refactor this for better clarity, consider making a header with a forward declaration of the array, i.e.

// modbusDefs40000.h
extern uint32_t defsMB40000[REG40000_SIZE];

and changing Python script to generate a complete declaration around the data portion of the initializer (i.e. two fixed lines - uint32_t defsMB40000[REG40000_SIZE] = { at the top and }; at the bottom. Call generated file modbusDefs40000.c, and use it along with other C files in your project.

Upvotes: 3

Related Questions