将编译时信息嵌入到二进制文件中
Embedding compile time information into binary
假设我有一个可变日期,在源代码中用extern定义,即extern date;
然后我想在 link 时间从编译它的计算机获取时间并分配给日期变量。
有没有办法在 gcc 中做到这一点?
__TIME__
和 __DATE__
是您要查找的内容吗?
如果编译和 linking 是您场景中的一个步骤,您可以让编译器和 linker 用日期和时间替换那些宏。如果你一天编译 link 另一天这将不起作用,因为编译器(更好:预处理器)决定插入哪个值。
查看 this 或 Whosebug 上的其他帖子。
可以在 link 命令之前将带有 date 命令输出的日期变量通过管道传输到 gcc 中,因此变量 date 包含 linkage 的当前日期和时间。 gcc 从 C 管道读取源代码的选项是 -xc -
.
/* hello.c */
#include <stdio.h>
int main(void)
{
extern char const date[];
printf("Hello, link date is %s\n", date);
return 0;
}
$ gcc -c hello.c
$ echo "char const date[] =\"`date`\";" | gcc -c -xc - -o date.o;gcc hello.o date.o
$ ./a.out
Hello, link date is Sat Jun 27 11:59:19 CEST 2015
$
假设我有一个可变日期,在源代码中用extern定义,即extern date; 然后我想在 link 时间从编译它的计算机获取时间并分配给日期变量。 有没有办法在 gcc 中做到这一点?
__TIME__
和 __DATE__
是您要查找的内容吗?
如果编译和 linking 是您场景中的一个步骤,您可以让编译器和 linker 用日期和时间替换那些宏。如果你一天编译 link 另一天这将不起作用,因为编译器(更好:预处理器)决定插入哪个值。
查看 this 或 Whosebug 上的其他帖子。
可以在 link 命令之前将带有 date 命令输出的日期变量通过管道传输到 gcc 中,因此变量 date 包含 linkage 的当前日期和时间。 gcc 从 C 管道读取源代码的选项是 -xc -
.
/* hello.c */
#include <stdio.h>
int main(void)
{
extern char const date[];
printf("Hello, link date is %s\n", date);
return 0;
}
$ gcc -c hello.c
$ echo "char const date[] =\"`date`\";" | gcc -c -xc - -o date.o;gcc hello.o date.o
$ ./a.out
Hello, link date is Sat Jun 27 11:59:19 CEST 2015
$