gcccompilationexecutableelffile-format

How can I generate an ELF file with GCC?


I am writing C and C++ code on Linux OS and I am using GCC.

After finishing my code, I would like to generate an ELF file. I just can generate a.out file and I don't need it.

How can I get an ELF file? What generates the ELF file?


Solution

  • The compiler (i.e. gcc or g++) will invoke the linker (ld) which produces an ELF executable.

    In practice, you will use a builder program (like make) to drive gcc commands. See this answer.

    The default output file for gcc is still named a.out (for historical reasons) but is an ELF file. And you really want to ask gcc to output an executable with a more fancy name.

    Simple example, you code a single-file hello-world.c program. You can compile it with e.g.

    gcc -Wall -g hello-world.c -o hello-world-bin
    

    (order of arguments to gcc matters a lot!)

    And the produced hello-world-bin is an ELF executable. Check with:

    file hello-world-bin
    

    Then run it with:

    ./hello-world-bin your arguments to it
    

    Later, learn how to use the gdb debugger on it.

    See also this and that answers.