bns
bns

Reputation: 113

gcc: Can you put function pointers to a different section (not .data)?

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.

Upvotes: 7

Views: 1714

Answers (1)

askmish
askmish

Reputation: 6684

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)

Upvotes: 2

Related Questions