29

I am not an expert C programmer and I know that including .c source file from another is considered bad practice, but I have a situation where I think it could help maintainability.

I have a big structure with a lot of elements and I use #define to keep the indexes.

#define TOTO_IND 0 
#define TITI_IND 1 
…
#define TATA_IND 50

static const MyElements elems [] = {
    {"TOTO", 18, "French"},
    {"TITI", 27, "English"},
    ...,
    {"TATA", 45, "Spanish"}
}

Since I need to access the structure from index, I need to keep the #define and the structure declaration synchronized. That means that I must insert new elements at the right place and update the #define accordingly.

It is error prone and I don’t really like it (but for performance consideration, I didn’t find a better solution).

Anyway, this file also contains a lot of functions to handle this structure. I also want to keep separation of code and avoid global variables.

To make things “easier”, I was thinking about moving this “error prone definition” to a single .c source file which would only contain this structure. This file would be “the dangerous be careful file” and include it in my actual “normal functional” file.

What do you think about it? Is it a valid situation for including .c source file? Is there another better way of handling my structure?

8
  • 21
    Even if the file contains a variable definition, you could still name the file with a .h ending. Oct 11, 2018 at 10:23
  • 8
    Maybe better if you name the file to be included as "file.inc" or "file.c.inc"?
    – pmg
    Oct 11, 2018 at 10:26
  • 12
    Are you aware that every other C file that requires the #definestuff, also will get its own copy of the array if this file is included?
    – Gerhardh
    Oct 11, 2018 at 10:33
  • 7
    What am I missing? Why don't you put the structure in its own .C file and extern it where you need to access it?
    – Mawg
    Oct 11, 2018 at 13:52
  • 2
    Would it be acceptable to declare the data together in one file of some format, then write a small utility (to run on the build system as part of the build process) to read that file and generate both a .c file and a .h file from that which are both marked with AUTOGENERATED - DO NOT TOUCH, EDIT source file name INSTEAD? Oct 12, 2018 at 1:05

5 Answers 5

40

You could use designated initializers to initialize the elements of elems[] without having to know the explicit value of each index identifier (or macro).

const MyElements elems[] = {
    [TOTO_IND] = {"TOTO", 18, "French"},
    [TITI_IND] = {"TITI", 27, "English"},
    [TATA_IND] = {"TATA", 45, "Spanish"},
};

The array elements will be initialized the same way, even if you change the order they appear in the source code:

const MyElements elems[] = {
    [TITI_IND] = {"TITI", 27, "English"},
    [TATA_IND] = {"TATA", 45, "Spanish"},
    [TOTO_IND] = {"TOTO", 18, "French"},
};

If the array length is set automatically from the initializer as above (i.e. by using [] rather than [NUM_ELEMS]), then the length will be the one more than the maximum element index.

This allows you to keep the index values and external declaration of the elems array in a .h file, and define the elems array contents in a separate .c file.

10
  • This is the correct answer in modern C. I posted an answer with additional advise based on this.
    – Lundin
    Oct 11, 2018 at 11:10
  • 2
    This still doesn't prevent OP from writing [TOTO_IND] = {"TITI", 27, "English"} though.
    – vgru
    Oct 11, 2018 at 11:43
  • 1
    @Groo The original was more error prone than this, I think. Adding comments to each element initializer to indicate which index symbol it is associated with would have helped, but designated initializers are better.
    – Ian Abbott
    Oct 11, 2018 at 13:50
  • 5
    important to note designated initialisers are a C99 feature, will not compile in C95, and cannot be used in C++11
    – cat
    Oct 11, 2018 at 15:09
  • 2
    To address @Groo's point, OP could use a macro (e.g. #define decl(idx, n, lang) [idx##_IND] = {#idx, n, lang}.
    – Kevin
    Oct 12, 2018 at 0:04
33

You should use designated initializers as shown in the answer by Ian Abbot.

Additionally, if the array indices are adjacent as seems to be the case here, you can use an enum instead:

toto.h

typedef enum
{
  TOTO_IND,
  TITI_IND,
  ...
  TATA_IND,
  TOTO_N    // this is not a data item but the number of items in the enum
} toto_t;

toto.c

const MyElements elems [] = {
  [TITI_IND] = {"TITI", 27, "English"},
  [TATA_IND] = {"TATA", 45, "Spanish"},
  [TOTO_IND] = {"TOTO", 18, "French"},
};

And now you can verify the data integrity of the array as whole with a static assert:

_Static_assert(sizeof elems/sizeof *elems == TOTO_N, 
               "Mismatch between toto_t and elems is causing rain in Africa");

_Static_assert(sizeof elems/sizeof *elems == TOTO_N, ERR_MSG);

where ERR_MSG is defined as

#define STR(x) STR2(x)
#define STR2(x) #x
#define ERR_MSG "Mismatching toto_t. Holding on line " STR(__LINE__)
13
  • Another possible integrity error is that some elements of elem might not have been initialized explicitly and so have default initializers. Run-time code should check for elements that haven't been initialized explicitly, since I don't think it can be done with _Static_assert.
    – Ian Abbott
    Oct 11, 2018 at 13:00
  • 7
    @GiacomoAlzetta It was a bad joke - rain in Africa is definitely a blessing. I have updated the question now, with an assert pointing out the offending line.
    – Lundin
    Oct 11, 2018 at 14:03
  • @IanAbbott They will be set to zero/NULL though, so if the code checks against that it should be ok. You can actually check if the initializer list contains the right number of items, with a somewhat dirty trick: Toss in something like typedef char BEGIN_CHECK[__LINE__]; just before the array declaration, then a similar one after. Static assert against the difference in size between the two types. But that trick does of course not take white space, comments etc in account.
    – Lundin
    Oct 11, 2018 at 14:57
  • should probably note that designated inits are a C99 feature and might not be suitable for embedded targets
    – cat
    Oct 11, 2018 at 15:11
  • 2
    @cat I would have done that 20 years ago, yes. Most embedded systems compilers today support C11. A few of them might still only support C99. Also the C (and C++) tag usage policy is that the current standard (C17) is assumed unless we are explicitly told otherwise by the OP.
    – Lundin
    Oct 11, 2018 at 15:13
18

Other answers have already covered it in a clearer way, but for completeness sake, here is an x-macros approach, if you are willing to go down this route and risk your coworker's rage.

X-macros are a form of code generation, using the built-in C preprocessor. The goal is to reduce repetition to a minimum, although with some drawbacks:

  1. Source file which generates enums and structures using the preprocessor might seem complex if you are not used to them.
  2. Compared to an external build script which would generate the source files, with x-macros you never get to see how the generated code looks like during compilation, unless you use a compiler setting and check for the preprocessed file manually.
  3. Since you don't see the preprocessed output, you cannot use the debugger to step through the generated code in the same way you would do with code generated by an external script.

You start by creating a list of macro invocations in a separate file, e.g. elements.inc, without defining what the macro actually does at this point:

// elements.inc

// each row passes a set of parameters to the macro,
// although at this point we haven't defined what the
// macro will output

XMACRO(TOTO, 18, French)
XMACRO(TITI, 27, English)
XMACRO(TATA, 45, Spanish)

And then you define the macro every time you need to include this list, so that each invocation gets rendered into a single row of the construct you want to create -- and you usually repeat this several times in a row, i.e.

// concatenate id with "_IND" to create enums, ignore code and description
// (notice how you don't need to use all parameters each time)
// e.g. XMACRO(TOTO, 18, French) => TOTO_IND,
#define XMACRO(id, code, description) id ## _IND,
typedef enum
{
#    include "elements.inc"
     ELEMENTS_COUNT
}
Elements;
#undef XMACRO

// create struct entries
// e.g. XMACRO(TOTO, 18, French) => [TOTO_IND] = { "TOTO", 18, "French" },
#define XMACRO(id, code, description) [id ## _IND] = { #id, code, #description },
const MyElements elems[] = {
{
#    include "elements.inc"
};
#undef XMACRO

Which will get preprocessed into something like:

typedef enum
{
    TOTO_IND,
    TITI_IND,
    TATA_IND,
    ELEMENTS_COUNT
}
Elements;

const MyElements elems[] = {
{
    [TOTO_IND] = { "TOTO", 18, "French" },
    [TITI_IND] = { "TITI", 27, "English" },
    [TATA_IND] = { "TATA", 45, "Spanish" },
};

Obviously, frequent maintenance of the list becomes easier, at the expense of the generating code becoming more convoluted.

5
  • 1
    Or just use TOTO etc for the enum, since you'll probably want those to correspond to 0 to n anyway. I think it is handy to have the index itself inside the x macro.
    – Lundin
    Oct 11, 2018 at 18:34
  • Very nice solution. A bit to confusing for me... I'll give it a try next time I need to refactor my code ;)
    – ncenerar
    Oct 12, 2018 at 9:42
  • 1
    @ncenerar: yes, these macros are often not recommended since it's hard to visualize how they are expanded and you cannot debug them, i.e. you cannot step through the code. However, this is basically a form of code generation, using the C preprocessor instead of an external tool. When you have repetitive data like this, you can also configure an external build script which will generate the code for you whenever you change the list, which is much better since you end up with actual "debuggable" code.
    – vgru
    Oct 12, 2018 at 9:49
  • Nice solution. You probably don't even need designated initializers since everything is put into the correct order by the #include "elements.inc". I'd probably have included the string directly in the 3rd parameter of the macro (replacing French with "French" and #description with description) in case the programmer wants to use something other than a string literal for that parameter.
    – Ian Abbott
    Oct 12, 2018 at 10:30
  • 3
    @Groo: An advantage of using the preprocessor is that it avoids the need for dependencies on any tools other than those required to build C programs, which can in turn facilitate porting to other build systems.
    – supercat
    Oct 12, 2018 at 14:54
5

Defining the const as static in multiple files is not a good idea because it creates multiple instances of the large variable MyElements. This will increase memory in an embedded system. The static qualifier needs to be removed.

Here is a suggested solution:

in file.h

#define TOTO_IND 0 
#define TITI_IND 1 
…
#define TATA_IND 50
#define MAX_ELEMS 51

extern const MyElements elems[MAX_ELEMS];

in file.c

#include "file.h"
const MyElements elems [MAX_ELEMS] = {
    {"TOTO", 18, "French"},
    {"TITI", 27, "English"},
    ...,
    {"TATA", 45, "Spanish"}
}

After modification, place #include "file.h" in the required .c files.

4
  • 1
    “Contradiction” is not the right word to describe a static const desired for use in multiple files. There are some benefits to it. Making the array externally linked instead prevents some optimizations. Oct 11, 2018 at 10:52
  • 3
    @EricPostpischil If the array is required in multiple files, making it static will have multiple copies of the array. The OP mentioned that the array had a large size, so this option was disregarded. Oct 11, 2018 at 11:00
  • you are right that static is bad here, but the way you phrase that line, sounds as though static for variables means the same as static function declarations (obviously it doesn't)
    – cat
    Oct 11, 2018 at 15:10
  • I have modified the text to explain further. Oct 15, 2018 at 4:01
1

To address the specific question about using #include with a .c file (the other answers suggest better options, especially the one by Groo), there is generally no need.

Everything in a .c file can be made externally visible and accessible, so you can reference it via function prototypes and #extern. So for example you could reference your table with #extern const MyElements elems []; in your main .c file.

Alternatively, you could put the definitions in a .h file and include that. That allows you to segregate the code as you want to. Keep in mind that all #include does is insert the contents of the included file where the #include statement is, so it's doesn't have to have any particular file extension. .h is used by convention and most IDEs will automatically add .c files to the list of files to be compiled, but as far as the compiler is concerned the naming is arbitrary.

1
  • Compile-time constants like enum cannot generally be imported via extern. When linking with other languages, such imports may be sometimes kludged via something like ``extern uint32_t addr_is_link_date;` #define unix_format_link_date ((uint32_t)&addr_is_link_date), which may be usable in some contexts that would otherwise require an integer constant [e.g. inclusion within a static const struct] but such cases are rare.
    – supercat
    Oct 12, 2018 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.