如何检查链接描述文件中是否定义了符号
我正在使用不同的链接描述文件。在某些情况下,定义了一个值,在其他情况下,未定义该值:
DIRECTORY_ADDRESS = 0x80100000;
DIRECTORY_SIZE = 32M;
在执行时,我希望在未定义该值时有默认行为,在定义该值时有特殊行为。
通常,我得到这样的值:
extern void * DIRECTORY_ADDRESS;
extern void * DIRECTORY_SIZE;
void f() {
void *dir_addr = &DIRECTORY_ADDRESS;
int dir_size = (int)&DIRECTORY_SIZE;
}
我第一个导致根据链接器脚本中该值的存在条件执行代码的是弱属性:
extern void * DIRECTORY_ADDRESS __attribute__ ((weak)) = 0x0;
extern void * DIRECTORY_SIZE __attribute__ ((weak)) = 0x0;
void f() {
if ( DIRECTORY_ADDRESS )
// special code
else
// default code
}
但它不起作用,因为我正在初始化指针值,而不是它的地址:即使是未定义的弱符号也有一个地址。所以目录地址总是!= NULL。
我很确定这个问题已经解决了,但我在网上找不到任何相关问题。
I am using different linker script. In some, a value is defined, in others, it is not defined:
DIRECTORY_ADDRESS = 0x80100000;
DIRECTORY_SIZE = 32M;
At execution, I want a default behavior when this value is not defined, and a special behavior when it is defined.
Classically, I get the values like this:
extern void * DIRECTORY_ADDRESS;
extern void * DIRECTORY_SIZE;
void f() {
void *dir_addr = &DIRECTORY_ADDRESS;
int dir_size = (int)&DIRECTORY_SIZE;
}
My first lead to conditionnaly execute code according to the existence of this value in linker script is the weak atttribute:
extern void * DIRECTORY_ADDRESS __attribute__ ((weak)) = 0x0;
extern void * DIRECTORY_SIZE __attribute__ ((weak)) = 0x0;
void f() {
if ( DIRECTORY_ADDRESS )
// special code
else
// default code
}
But it can't work, as I am initializing the pointer value, and not its address: even an undifined weak symbol has an address. So directory address is always != NULL.
I am pretty sure this problem has already been solved, but I can't find any related problem on the web.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的错误!
我尝试了很多组合,而这个实际上是错误的:
当我初始化弱符号时,有“半弱”
要解决我的问题,我只需让弱符号未初始化,那么如果它们不是,则符号地址将为NULL用强符号定义:
My mistake!
I tried many combination, and this one is actually wrong:
As I am initliazing weak symbols, there are "half weak"
To solve my problem, I just have to let weak symbols uninitialized, then the symbol address will be NULL if they are not defined with a strong symbol:
默认情况下,未初始化的全局变量很弱,因此您可以只使用
如果没有为这些名称定义外部符号,则该值将默认为 NULL。要强制使用与 NULL 不同的默认值,您可以使用
注意初始化
extern
并没有真正意义:extern
意味着定义位于文件外部,但初始化提供了定义。我的编译器 (gcc 4.4) 向用户发出警告,然后忽略 extern 修饰符。这意味着您的示例按我的预期工作(即使初始化为 0x0),但也许您的编译器以不同的方式处理这种不明确的情况。Uninitialized globals are weak by default, so you can just use
If there is no external symbol defined for these names, the value will default to NULL. To force a different default value than NULL, you could use
Note that initializing an
extern
doesn't really make sense:extern
means that the definition is external to the file, but initializing provides a definition. My compiler (gcc 4.4) warns the user of this, and then ignores theextern
modifier. This means your example worked as expected for me (even when initializing to 0x0), but maybe your compiler handles this ambiguous situation differently.