For doing Unit Testing of an embedded project on the host, I started to use function pointers to be able to change between the 'real' implementation of a function and a mock at runtime. So, my function 'foo' looks like this in the .c file:
// the 'real' implementation of the function to be used during runtime
void fooImplementation ( )
{
/* ... */
}
// the function pointer, initialized to the 'real' implementation
void (*foo) ( ) = fooImplementation;
It came out that the target processor (Blackfin) generates an exception, because the function pointer resides in the internal L1 data memory which isn't allowed to carry code but only data.
A solution that works is to assign an attribute to each function pointer so it is put into a different section that doesn't reside in L1 data memory, e.g.:
void (*foo) ( ) __attribute__ (( section(".ext_mem"))) = fooImplementation;
But this makes the code a little bit hard to read and is error prone (if you forget to assign the attribute, unit tests will run fine but the code will generate the exception as soon as the function is called on the target).
So my question is if there is some way to tell gcc to put all function pointers to a different section by default.
2. What will we not do with function pointers? Explanation: As it is used to execute a block of code, So we will not allocate or deallocate memory.
(A) It is passed as a hidden argument to all function calls (B) It is passed as a hidden argument to all non-static function calls (C) It is passed as a hidden argument to all static functions (D) None of the above Answer: (B) Explanation: The this pointer is passed as a hidden argument to all non-static member We ...
C programming allows passing a pointer to a function. To do so, simply declare the function parameter as a pointer type.
As I understand function pointer is a pointer variable that stores address of a function however pointer to a function is a function which takes function pointer as an argument.
There is no such option, in gcc, to specially put all function pointers in a particular section, by default. Unless, ofcourse you rewrite the compiler and linker rules.
You have to use the __attribute__
keyword, as you mentioned in the question. If the code looks complex, you could create a macro around it:
#define SPECIAL_FOO(x) void (*x) ( ) __attribute__ (( section(".ext_mem")))
and then use it like this:
SPECIAL_FOO(foo) = fooImplementation;
There's however another way, too. You could see this SO thread to understand more about creating custom linker scripts to accomplish your task:Forcing certain compiler-generated variables into specific ELF sections (with gcc)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With