0

Up to now I use #define to map functions.

Exemple: if I have 2 physical uarts, to map SendDebugString to the matching physical uart I use:

#define SendDebugString(s) Uart1_SendDebugString(s)   // map to uart 1

or

#define SendDebugString(s) Uart2_SendDebugString(s)   // map to uart 2

How can I do the same using function pointers instead of #define?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Mich
  • 119
  • 1
  • 8

1 Answers1

4

Let say the function signature is int sendString(char* s). You can then write:


// declare SendDebugString as a pointer to a function
// accepting a string as argument and returning an int
int (*SendDebugString)(char *s);

// assign a function to SendDebugString
SendDebugString = Uart1_SendDebugString;

// call the function
SendDebugString("hello world!");
chmike
  • 20,922
  • 21
  • 83
  • 106
  • If I write in a definition file uartPack.h : int (*SendDebugString)(char *s); If this file is called from other many files I have: Error[e27]: Entry "SendDebugString" in module ... redefined in module .... – Mich Dec 04 '19 at 10:07
  • 1
    @Mich you have to put `extern` in front of `int (*SendDebugString)(char *s);` in the `uartPack.h` file, and in the `uartPack.c` you put `int (*SendDebugString)(char *s);` without the `extern` keyword. – chmike Dec 04 '19 at 10:10
  • 1
    @Mich If the function pointer is global, the same rules apply as for any other global variable (like an `int`): it must be defined in one source file, and declared in the header with `extern`. – user253751 Dec 04 '19 at 14:55