3

A little bit of context first. My program features a header, work.h. This header contains a structure, some function definitions, and an extern array of pointers to my base functions.

work.h

typedef struct _foo {
  int id;
  char something[20];
} foo;

typedef void (*pointer_function)(foo *);

void do_first_to_foo(foo *);

void do_second_to_foo(foo *);

void do_third_to_foo(foo *);

extern pointer_function base_functions[3];

Then a program called work.c with the bodies of the functions, and then the main program main.c. Observe in the header work.h that I have defined prototypes of three functions, and the size of the array is 3, so the pointers on the extern array will point to each one of the 3 functions.

My questions are, how I can associate the pointers of the extern array with the three functions, and second, in which file I need to do it (work.c or main.c).

I understand this association I need to do it in the file work.c, but nothing else.

1 Answer 1

6

In work.c:

#include "work.h"

pointer_function base_functions[] = {
    do_first_to_foo,
    do_second_to_foo,
    do_third_to_foo };

Explanation: that array name is a global symbol, and needs to be actually defined in just one compilation unit (.o file produced from .c file). If you do not have it, linker will not find it. If you have multiple copies, linker will complain. You need just one, same as with global exported functions (which are not marked inline).

Edit: Added showing #include "work.h", which is important because it allows compiler to check that extern declaration matches the actual definition. If you leave it out, everything will compile and link without complaints, but you get no indication if there's a mismatch, which could wreak havoc like corrupt other data in memory when variable is used in other compilation units.

Sign up to request clarification or add additional context in comments.

3 Comments

Beat me by this much ><.
One more thing I need to ask. If I have to call some of the functions in the pointer array in main.c , how I need to do it?
@CristianC. Just stick () after pointer expression, so with array of function pointers: arr[ind](param);

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.