Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C append to an array in header file

Tags:

c

I have multiple header files, each of them must append a number to an array to register it's functions.

Currently I have a function with a unique name in each header file, and in the program file I need to call all those functions in one combining function.

int register1() { return 100; }; //in header1.h
int register2() { return 200; }; //in header2.h
int register3() { return 300; }; //in header3.h
int register4() { return 400; }; //in header4.h
int registered[] = {register1(),register2(),register3(),register4()}; //main.c

But this is quite inconvenient because I need to modify in two places when I add or remove header files. Better would be to modify the header file only. I was thinking about a preprocessor define, so in each header I can just use something like:

#define Registered Registered,100 // header1.h
#define Registered Registered,200 // header2.h
int registered[] = {Registered}; // main.c

But this of course will not compile, because new define redefines the old one. So is there a way to append a define? Or other way to append a number to an array without modifying two files?

This is C, not C++, otherwise I would use a class instance with constructor that would just write to an array. Somethink like that:

struct __header1{ __header1() { 
   global_array[global_array_ptr++] = 100; 
} } __header1_inst;

and then convert it to a nice macro:

    #define register(hdr, func) struct __header##hdr{ __header##hdr() { \
       global_array[global_array_ptr++] = func; \
    } } __header##hdr##_inst;

   register(1, 100) // header1.h
   register(2, 200) // header2.h
like image 782
exebook Avatar asked Nov 13 '22 04:11

exebook


1 Answers

IMHO, this is a hack and I would advise against it. Even if you could do that in C, consider situation where one such header file is included by several modules. There will be an identical entry in the global array for every such module. Next, even though you can do it in C++, the order of global object initialization is undefined there, so initialization of another global object relying on contents of the global array will be unreliable.

Additionally, this is a really complicated way to do a simple thing, and obscures the meaning considerably. Apart from the array-filling code itself being complex, tracking includes will become burdensome when dependencies get beyond trivial. So, just fill that global array in a specific place explicitly.

like image 152
spbnick Avatar answered Nov 14 '22 22:11

spbnick