问题描述
在 LJ帖子中,--defsym
标志用于将构建日期传递到源代码中:
In an LJ post, the --defsym
flag was used for passing the build date into the source code:
#include <stdio.h>
extern char __BUILD_DATE;
void main(void) {
printf("Build date: %u\n", (unsigned long) &__BUILD_DATE);
}
通过链接以下标志:
gcc example.c -Xlinker --defsym -Xlinker __BUILD_DATE=$(date +%Y%m%d)
根据 ld手册,
我试图了解以下内容:
- 构建日期(
YYYYmmdd
+\0
)的9个字符的字符串如何存储在内存中? - 如果
--defsym
创建包含地址的符号,为什么将__BUILD_DATE
定义为字符而不是指针或整数类型? - 为什么将
__BUILD_DATE
定义为char
而不是unsigned long
(如果最终将其强制转换为unsigned long
?)?
- How is the 9-character string for the build date (
YYYYmmdd
+\0
) stored in memory? - If
--defsym
creates a symbol containing an address, why__BUILD_DATE
is defined as a char and not as a pointer or as an integral type? - Why
__BUILD_DATE
is defined aschar
and notunsigned long
if it is eventually casted tounsigned long
?
推荐答案
链接器将全局变量视为地址(指向实际"全局变量而不是实际全局变量的指针-即使该地址中不存在实际全局变量) . -Xlinker --defsym -Xlinker __BUILD_DATE=$(date +%Y%m%d)
设置地址of __BUILD_DATE
而不是值.当__BUILD_DATE
链接程序实体具有地址但没有值时,可以通过将该实体声明为任何东西,然后获取该地址来获取该地址.
Linkers see globals as addresses (pointers to the "actual" global rather than the actual global -- even if the actual global doesn't exist at that address). -Xlinker --defsym -Xlinker __BUILD_DATE=$(date +%Y%m%d)
sets the address of __BUILD_DATE
not the value. When the __BUILD_DATE
linker entity has an address but not a value, you can get the address by declaring the entity as anything and then taking the address of that.
在:
#include <stdio.h>
//extern long __BUILD_DATE[128];
//extern int __BUILD_DATE;
extern char __BUILD_DATE;
int main(void)
{
printf("Build date: %lu\n", (unsigned long)&__BUILD_DATE);
}
三个声明中的任何一个都应该起作用.只是不要尝试使用该(伪)全局值.就像取消引用无效的指针一样.
Any of the three declarations should work. Just don't try to use the value of that (pseudo) global. That would be like dereferencing an invalid pointer.
应该回答2和3.要回答1,-Xlinker --defsym -Xlinker __BUILD_DATE=$(date +%Y%m%d)
将$(date %Y%m%d)
返回的数字(stdout)存储为的地址.它不存储字符串.
That should answer 2 and 3. To answer 1, -Xlinker --defsym -Xlinker __BUILD_DATE=$(date +%Y%m%d)
stores the number returned (stdout) by $(date %Y%m%d)
as the address of __BUILD_DATE
. It doesn't store a string.
这篇关于--defsym链接器标志如何将值传递给源代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!