views:

82

answers:

2

Hi,

i have an array (C language) that should be initialized at compile time.

For example:

DECLARE_CMD(f1, arg);
DECLARE_CMD(f2, arg);

The DECLARE_CMD is called from multiple files.

I want this to be preprocessed in.

my_func_type my_funcs [] = {
   &f1,
   &f2
}

It is possible, with a macro, to append items to an static array?

I am using C99 (with GNU extensions) on gcc4.

+2  A: 

NOTE: in your question there are semicolons at the end of every line. This will seriously interfere with any attempt to use these macros. So it depends on where and how the DECLARE_CMD(...) lines are found, and whether you can fix the semicolon problem. If they are simply in a dedicated header file all by themselves, you can do:

#define DECLARE_CMD(func, arg) &func,

my_func_type my_funcs [] {
    #include "file_with_declare_cmd.h"
};

...which gets turned into:

my_func_type my_funcs [] {
    &f1,
    &f2,
};

Read The New C: X Macros for a good explanation of this.

If you can't get rid of the semicolons, this will be processed to:

my_func_type my_funcs [] {
    &f1,;
    &f2,;
};

... which is obviously a syntax error, and so this won't work.

detly
So i should move all the DECLARE_CMD in headers -- it would be nice if i don't do this, because the directory structure is quite complex. Another problem is that even the my_funcs variable is generated by a macro, so it's trickier to include multiple headers.
cojocar
@cojocar — "So i should move all the DECLARE_CMD in headers" ... I would say yes, otherwise I can't think of a structured way to do it. Think about it: there's no way for the preprocessor to hunt around your source tree for occurrences of `DECLARE_CMD`. You need to explicitly tell it where to look.
detly
You could always `grep` them out of the entire source tree into a temp file that is `#include`d similar to the pattern above to define your table, using a build rule specific to a single target.
RBerteig
+1  A: 

Yes, it is possible. The usual trick is to have all the DECLARE_CMD(func, args) lines in one (or more) include files, and to include those in various places with an appropriate definition for the macro.

For example:

In file 'commands.inc':

DECLARE_CMD(f1, args)
DECLARE_CMD(f2, args)

In some source file:

/* function declarations */
#define DECLARE_CMD(func, args) my_func_type func;
#include "commands.inc"
#undef DECLARE_CMD

/* array with poiners */
#define DECLARE_CMD(func, args) &func,
my_func_type* my_funcs[] = {
    #include "commands.inc"
    NULL
};
Bart van Ingen Schenau