1

My question is quite close to this one: How do you declare a const array of function pointers?

I successful created static const function pointer arrays in an include file on mine.

void fun1( void* );
void fun2( void* );
typedef void ( *funPointer )( void* );
funPointer myFunPointer[2] = { &fun1, &fun2 };

Now I found the following: my compiler (gcc 4.6.3) complains when I

(1) compile different *.o files with this header included and afterwards linking them together (multiple definition) - it helps to use static keyword within the declaration of the array (EDIT: actually the functions must be declared static).

(2) compile a file with the header included and not setting the array const. (myFunPointer declared but not used)

static const myFunPointer[2] ....

Seizes both errors/warnings.

Now the question: I can explain the former behavior, since static uses a "predefined" memory address and several declarations of the function will merge at the address. Is this explanation correct? How can the absence of the warning for const declaration be explained? Is it a the ability of the compiler to remove the unnecessary section of the file automatically...?

Community
  • 1
  • 1
0815ZED
  • 123
  • 1
  • 12

1 Answers1

6

In your header file...

void fun1( void* );
void fun2( void* );
typedef void ( *funPointer )( void* );
extern funPointer myFunPointer[2];

and in one of your source files...

funPointer myFunPointer[2] = { fun1, fun2 };
K Scott Piel
  • 4,320
  • 14
  • 19
  • OK, its like a function template then? I mustn't write the whole function body into a header and compile it a bazillion times but give the compiler a structure and leave the actual work to the linker...!? – 0815ZED Apr 24 '13 at 18:22
  • 3
    myFunPointer is just a variable... an array holding two funPointers. When you declare that variable in the header, then every source file that includes the header tries to create a copy of the variable... so you end up with multiple copies of the variable. You only need one copy that everyone can share... so you declare it extern in the header and then only create a single instance of it in a single source file. – K Scott Piel Apr 24 '13 at 18:24