bns*_*bns 6 c embedded gcc pointers linker-scripts
为了对主机上的嵌入式项目进行单元测试,我开始使用函数指针来在函数的"真实"实现和运行时的模拟之间进行切换.所以,我的函数'foo'在.c文件中看起来像这样:
// the 'real' implementation of the function to be used during runtime
void fooImplementation ( )
{
/* ... */
}
// the function pointer, initialized to the 'real' implementation
void (*foo) ( ) = fooImplementation;
Run Code Online (Sandbox Code Playgroud)
结果是目标处理器(Blackfin)产生异常,因为函数指针驻留在内部L1数据存储器中,不允许携带代码而只允许数据.
一个有效的解决方案是为每个函数指针分配一个属性,以便将它放入不在L1数据存储器中的不同部分,例如:
void (*foo) ( ) __attribute__ (( section(".ext_mem"))) = fooImplementation;
Run Code Online (Sandbox Code Playgroud)
但是这使得代码有点难以阅读并且容易出错(如果您忘记分配属性,单元测试将运行正常,但代码将在目标上调用函数后立即生成异常).
所以我的问题是,如果有一些方法告诉gcc默认将所有函数指针放到不同的部分.
默认情况下,gcc 中没有这样的选项来专门将所有函数指针放在特定的部分中。当然,除非您重写编译器和链接器规则。
__attribute__正如您在问题中提到的,您必须使用关键字。如果代码看起来很复杂,您可以围绕它创建一个宏:
#define SPECIAL_FOO(x) void (*x) ( ) __attribute__ (( section(".ext_mem")))
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
SPECIAL_FOO(foo) = fooImplementation;
Run Code Online (Sandbox Code Playgroud)
不过,还有另一种方法。您可以看到这个 SO 线程来了解有关创建自定义链接器脚本来完成您的任务的更多信息:Forcing certain Compiler-Generate Variables into Specific ELFsections (with gcc)