Automatically generate table of function pointers in C.

Posted by jeremytrimble on Stack Overflow See other posts from Stack Overflow or by jeremytrimble
Published on 2010-03-19T21:54:36Z Indexed on 2010/03/19 22:01 UTC
Read the original article Hit count: 487

I'm looking for a way to automatically (as part of the compilation/build process) generate a "table" of function pointers in C.

Specifically, I want to generate an array of structures something like:

typedef struct {
  void (*p_func)(void);
  char * funcName;
} funcRecord;

/* Automatically generate the lines below: */

extern void func1(void);
extern void func2(void);
/* ... */

funcRecord funcTable[] =
{
  { .p_func = &func1, .funcName = "func1" },
  { .p_func = &func2, .funcName = "func2" }
  /* ... */
};

/* End automatically-generated code. */

...where func1 and func2 are defined in other source files.

So, given a set of source files, each of which which contain a single function that takes no arguments and returns void, how would one automatically (as part of the build process) generate an array like the one above that contains each of the functions from the files? I'd like to be able to add new files and have them automatically inserted into the table when I re-compile.

I realize that this probably isn't achievable using the C language or preprocessor alone, so consider any common *nix-style tools fair game (e.g. make, perl, shell scripts (if you have to)).

But Why?

You're probably wondering why anyone would want to do this. I'm creating a small test framework for a library of common mathematical routines. Under this framework, there will be many small "test cases," each of which has only a few lines of code that will exercise each math function. I'd like each test case to live in its own source file as a short function. All of the test cases will get built into a single executable, and the test case(s) to be run can be specified on the command line when invoking the executable. The main() function will search through the table and, if it finds a match, jump to the test case function.

Automating the process of building up the "catalog" of test cases ensures that test cases don't get left out (for instance, because someone forgets to add it to the table) and makes it very simple for maintainers to add new test cases in the future (just create a new source file in the correct directory, for instance).

Hopefully someone out there has done something like this before. Thanks, StackOverflow community!

© Stack Overflow or respective owner

Related posts about c

    Related posts about build-process