如何编写可执行文件中所需的信息

时间:2015-09-22 13:15:35

标签: gcc compilation comments executable xlc

我想知道您是否知道在可执行文件中写入注释或字符串的命令或方法。 事实上我已经用 XLC 编译器完成了这个,我用#pragma comment(user, "string")做了但是现在我必须更改为 GCC 但是在下有一个问题GCC #pragma无法识别。

我的问题是,你知道另一个#pragma谁可以在gcc下完成它,或者只是另一种方法来处理以便在编译时恢复写在可执行文件中的信息。

谢谢,Ežekiel

2 个答案:

答案 0 :(得分:0)

这是一个快速解决方案.c / c ++程序中的字符串文字通常放在ELF文件的只读段中。

假设您的评论遵循以下模式:

My_Comment: .... 

您可以在程序中添加一些字符串定义:

#include <stdio.h>

void main() {

    char* a = "My Comment: ...";
}

编译:

$ gcc test.c

然后在可执行文件中搜索您的评论模式:

$ strings a.out | grep Comment
My Comment: ...

我可以问一下将注释嵌入可执行文件的用例是什么?

跟进:

如果使用-O3标志进行编译,则此未使用的字符串将被优化,因此它不会存储在ro数据中。基于同样的想法,你可以通过以下方式欺骗gcc:

#include <stdio.h>

void main() {

    FILE* comment = fopen("/dev/null", "w");
    fprintf(comment, "My Comment:");
}

然后搜索您的评论。当然,你可以获得2或3个系统调用的开销,但希望你可以忍受它。

让我知道这是否有效!

答案 1 :(得分:0)

在AIX上使用 xlC_r 系列编译器将某些特定信息放入可执行文件的另一种方法是

#pragma comment(copyright, "whatever")

如果你想要什么样式字符串,那么我建议:

// the Q(S) macro uses ANSI token pasting to get the _value_
// of the macro argument as a string.
#define Q(S) Q_(S)
#define Q_(S) #S
// breaking up the "@(" and "#)" prevent `what` from finding this source file.
#define WHAT(MODULE,VERSION) "@(" "#) " Q(VERSION) " " Q(MODULE) " " __DATE__ " " __TIME__
#pragma comment(copyright, WHAT(ThisProgram,1.2.3.4))

或者您嵌入的任何特殊字符串。

更新: gcc

请参见用户2079303的答案:gcc equivalent of #pragma comment

使用内联汇编程序将字符串添加到 .comment 部分

__asm__(".section .comment\n\t"
        ".string \"Hello World\"\n\t"
        ".section .text");

更新:对于AIX gcc

在AIX gcc内联汇编程序中,这似乎更好,可以在 .comment 部分添加字符串

__asm__(".csect .comment[RO]\n\t"
        ".string \"Hello World\"\n\t"
        ".csect .text[PR]");
相关问题