Search code examples
gcccompilationcommentsexecutablexlc

How to write informations needed in an executable file


I wanted to know if you knew a command or a way to write as comment or string inside of the executable file. Indeed I already did this, with XLC compiler I did it with the #pragma comment(user, "string") however now I have to change to GCC but there's a problem, under GCC this #pragma is not recognized.

My question is, do you know another #pragma who can do it under gcc, or just another way to process to recover an information written in the executable file when I compile.

Thanks, Ežekiel


Solution

  • Here is a quick solution.String literals in a c/c++ program, are usually put into the read-only segment of the ELF file.

    Assuming that your comment follows a pattern:

    My_Comment: .... 
    

    you could add some string definitions in your program:

    #include <stdio.h>
    
    void main() {
    
        char* a = "My Comment: ...";
    }
    

    compile:

    $ gcc test.c
    

    and then search for your comment pattern in the executable:

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

    may I ask what is the use case of embedding comments into an executable?

    Follow up:

    If you are compiling with the -O3 flag, this unused string is optimized out, so it is not stored at all in the ro data. Based on the same idea, you could fool gcc by:

    #include <stdio.h>
    
    void main() {
    
        FILE* comment = fopen("/dev/null", "w");
        fprintf(comment, "My Comment:");
    }
    

    Then search for your comment. You get the overhead of 2 or 3 system calls of course, but hopefully you can live with it.

    Let me know if this works!