--defsym链接器标志如何将值传递给源代码? [英] How does the `--defsym` linker flag work to pass values to source code?

查看:424
本文介绍了--defsym链接器标志如何将值传递给源代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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手册

--defsym symbol=expression在输出文件中创建一个全局符号,其中包含表达式给出的绝对地址.

--defsym symbol=expression Create a global symbol in the output file, containing the absolute address given by expression.

我试图了解以下内容:

  1. 构建日期(YYYYmmdd + \0)的9个字符的字符串如何存储在内存中?
  2. 如果--defsym创建包含地址的符号,为什么将__BUILD_DATE定义为字符而不是指针或整数类型?
  3. 为什么将__BUILD_DATE定义为char而不是unsigned long(如果最终将其强制转换为unsigned long?)?
  1. How is the 9-character string for the build date (YYYYmmdd+\0) stored in memory?
  2. 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?
  3. Why __BUILD_DATE is defined as char and not unsigned long if it is eventually casted to unsigned 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)存储为<​​c5>的地址.它不存储字符串.

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链接器标志如何将值传递给源代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆