How to retrieve the GCC version used to compile a given ELF executable?

Ilyes Gouta picture Ilyes Gouta · Mar 5, 2010 · Viewed 51.2k times · Source

I'd like to retrieve the GCC version used to compile a given executable. I tried readelf but didn't get the information. Any thoughts?

Answer

technosaurus picture technosaurus · Mar 12, 2012

It is normally stored in the comment section

strings -a <binary/library> |grep "GCC: ("

returns GCC: (GNU) X.X.X

strip -R .comment <binary>
strings -a <binary/library> |grep "GCC: ("

returns no output

It is not uncommon to strip the .comment (as well as .note) section out to reduce size via

strip --strip-all -R .note -R .comment <binary>
strip --strip-unneeded -R .note -R .comment <library>

Note: busybox strings specifies the -a option by default, which is needed for the .comment section

Edit: Contrary to Berendra Tusla's answer, it does not need to be compiled with any debugging flags for this method to work.

Binary example:

# echo "int main(void){}">a.c
# gcc -o a a.c -s
# strings -a a |grep GCC
GCC: (GNU) 4.3.4
# strip -R .comment a
# strings -a a |grep GCC
#

Object example:

# gcc -c a.c -s
# strings -a a.o |grep GCC
GCC: (GNU) 4.3.4
# strip -R .comment a.o
# strings -a a |grep GCC
#

Note the absence of any -g (debugging) flags and the presence of the -s flag which strips unneeded symbols. The GCC info is still available unless the .comment section is removed. If you need to keep this info intact, you may need to check your makefile (or applicable build script) to verify that -fno-ident is not in your $CFLAGS and the $STRIP command lacks -R .comment. -fno-ident prevents gcc from generating these symbols in the comment section to begin with.