【问题标题】:C Makefile: How to build environment variable into executableC Makefile:如何将环境变量构建为可执行文件
【发布时间】:2022-06-30 22:35:04
【问题描述】:

我试图在编译时将环境变量从 shell 传递到可执行文件中,并能够访问该变量。例如,假设我想在构建应用程序时将某些东西编译到应用程序中,这样我就可以看到构建可执行文件的时间。我如何构建 Makefile 和 C 程序来做到这一点?

示例 C 程序:

#include <stdio.h>
#define variable 2

void main(){
printf("Variable: %d\n", variable);
}

示例生成文件:

CC=gcc
CFLAGS=-I
BUILD_TIME=$(date)
example: example.c
        $(CC) -o example example.c

如何修改这两个文件以使 BUILD_TIME 变量可用于 C 文件?

【问题讨论】:

  • 在命令行上定义预处理器宏的选项对您有帮助吗?
  • variable写入main.cincludes的文件。您可以在编译前更新variable

标签: c makefile environment-variables


【解决方案1】:

您可以使用-D 选项在命令行上创建预处理器变量。

CC=gcc
CFLAGS=-I
BUILD_TIME=$(date)
example: example.c
        $(CC) -D "BUILD_TIME=\"$(BUILD_TIME)\"" -o example example.c
#include <stdio.h>

int main()
{
    printf("build time = %s\n", BUILD_TIME);
    return 0;
}

【讨论】:

  • 注意:它不会是整数,所以 OP 需要调整他们的printf 格式字符串。
猜你喜欢
  • 1970-01-01
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
  • 2014-04-25
  • 1970-01-01
相关资源
最近更新 更多