问题
I'm trying to write a macro that adds a comment to an executable with the gcc compiler. This is not for linking purposes, I simply want to add text comments. Is there a #pragma comment equivalent in gcc for this purpose?
回答1:
I'm not sure what it means to "add a comment to an executable". Who or what is going to consume, display, or even notice such comments? Nevertheless, if you just want to ensure some string is embedded somewhere in your program, then simply declare it as an ordinary (C) string at file scope.
static const char my_comment[] = "This comment should appear in the compiled executable";
回答2:
If you don't want to clutter the .data
section (which is where the static const char[]
would go) with comments or conversely, want the comments to be found easily from the .comment
section, you can add the comments there with a little bit of inline assembly:
__asm__(".section .comment\n\t"
".string \"Hello World\"\n\t"
".section .text");
Gcc also has #ident
directive which copies the text into an appropriate section if available. In the case of ELF, it would be the .comment section. This solution, even though the directive isn't standard, is probably more portable than the former.
#ident "Hello World"
回答3:
#ident may be useful. But there are two caveats :
- It may not work on all targets.
- This is neither a C language standard nor a GNU coding standard
The ‘#ident’ directive takes one argument, a string constant. On some systems, that string constant is copied into a special segment of the object file. On other systems, the directive is ignored. The ‘#sccs’ directive is a synonym for ‘#ident’.
These directives are not part of the C standard, but they are not official GNU extensions either.
https://gcc.gnu.org/onlinedocs/cpp/Other-Directives.html
来源:https://stackoverflow.com/questions/25572356/gcc-equivalent-of-pragma-comment