如何在可执行文件中查看宏定义值

How to view Macro definition value in executable

本文关键字:宏定义 可执行文件      更新时间:2023-10-16

自从我用C/C 编码以来已经有几年了,对NewBie'ish问题感到抱歉。我的代码库可以根据通过#Defines定义的配置进行不同的编译,这些配置可以作为ARG提供给Makefile。有没有一种方法来编码这些#Defines,以便我可以查看可执行文件并查看定义是什么 - 例如。

int main() {
  #ifdef CONFIG_A
    init_config_a();
  #endif
  #ifdef CONFIG_B
    init_config_b();
  #endif
}
#ifdef CONFIG_A
void init_config_a() {
  // do something
}
#endif
#ifdef CONFIG_B
void init_config_b() {
  // do something for B
}
#endif

我如何确定是否使用config A或config B创建给定的可执行文件。一个hack是寻找仅根据定义(例如init_config_a(编译的符号,但这很丑陋。

>

编辑:对不起,我忽略了一个重要的信息:该程序实际上是在嵌入式系统上运行的,因此我不能轻易地添加开关或某些其他机制来本地运行该程序。

<</p>

好吧,您的问题并不是真正要在使用二进制后真正想要获取信息的真正精确的。作为不涉及拆卸的解决方案,将在您要打印该信息时具有该信息的结构并初始化。也许像这样很重要:

#include <stdio.h>
#include <string.h>
struct buildinfo {
    int CONFIG_A;
    int CONFIG_B;
};
void get_build_info(struct buildinfo *info)
{
    if(info == NULL)
        return;
    memset(info, 0, sizeof *info);
#ifdef CONFIG_A
    info->CONFIG_A = 1;
#endif
#ifdef CONFIG_B
    info->CONFIG_B = 1;
#endif
}
int main(int argc, char **argv)
{
    if(argc == 2 && strcmp(argv[1], "-v") == 0)
    {
        struct buildinfo info;
        get_build_info(&info);
        printf("build info: CONFIG_A: %s, CONFIG_B: %sn",
                info->CONFIG_A ? "yes" : "no",
                info->CONFIG_B ? "yes" ; "no");
        return 0;
    }

    ...

    return 0;
}

我不想分析二进制文件,然后您可以执行./yourprogram -v并查看屏幕上打印的信息。

  1. 最好的方法是根据所使用的定义命名二进制。
  2. 如果您只想通过检查使用CONFIG_A还是CONFIG_B构建二进制文件。在可能的方法上可能是以下内容。根据特定地址的配置放置签名(也将在任何地址上工作(。例如

    int main() {
    #ifdef CONFIG_A
    // this sign can be put at specific address with #pragma
    const char sign[]="CONFIG_A";
    init_config_a();
    #elif defined(CONFIG_B)   // only one shall be defined at a time 
    // this sign can be put at specific address with #pragma
    const char sign[]="CONFIG_B";
    init_config_b();
    #endif
    }
    

当您在文本编辑器中打开二进制文件时,您将可以在ASCII视图中看到符号。

相关文章: