gcc

Cheatsheet

Most useful commands (especially for me:)

  1. Create position independent code( -fPIC)

gcc -c -fPIC file.c
  1. Use compile line macros (-Dmacro)

gcc -DMACRO file.c
  1. Convert warnings to errors (-Werror)

gcc -Werror file.c
  1. Gcc options through a file using @option usefull if you use many options. Example file:

-Werroe -Wall
gcc file.c @file_contains_options
  1. Strip the content

gcc -s file.c -o file
  1. Add debugging information

gcc -g file.c -o file
  1. Generate Makefile

gcc -MM file.c
  1. Specify architecture

gcc -m32 file.c
  1. Without rbp register

gcc -fomit-frame-pointer file.c
  1. Get pretty assembly output

gcc file.c -S -masm=intel -fverbose-asm -o file.S

Get compiling stages

  1. Get pre-processed output from file.c -> file.i

gcc -E file.c
  1. Compilation from file.i -> file.s

gcc -S file.i -o file.S
  1. Assembly

gcc -c file.S -o file.o
  1. Linking

gcc file.o -o file
  1. Get all intermediate files using (-save-temps)

gcc -save-temps file.c
  1. Linking with shared libraries (-l)

gcc file.c -o file -lCPPFILE
  1. Produce only compiled code

gcc -c file.c
  1. This enables all the warnings about constructions that some users consider questionable. Compile every program with this flag.

gcc -Wall file.c

Include source code in asm output:

gcc test.c -o test -Wa,-adhln=test.s -g -fverbose-asm -masm=intel

Special commands

  1. Disable stack protection. Usefull when you learn buffer overflow.

gcc -fno-stack-protection
  1. Use fpu registers. Usefull when you learn x87 FPU Coproccesor commands

gcc -mno-sse

Print (on standard error output) the commands executed to run the stages of compilation. Also print the version number of the compiler driver program and of the preprocessor and the compiler proper. Can get information about where include files was searched.

gcc -v file.c
  1. Don't produce a position independent executable. There is problem when compiling some programs.

gcc -no-pie file.c

Debian switched to PIC/PIE binaries in 64-bits mode & GCC in your case is trying to link your object as PIC

For more details see https://stackoverflow.com/questions/48071280/nasm-symbol-printf-causes-overflow-in-r-x86-64-pc32-relocation

  1. Do not search the standard system directories for header files. Only the directories explicitly specified with flags.

gcc -nostdinc
gcc -c hello.c -o hello.o
ar -cvq libhello.a hello.o
gcc -o res main.c libhello.a
  1. Print the full absolute name of the library

gcc -print-file-name=libc.so

output: /usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/libc.so

Compiler Level

https://gcc.gnu.org/onlinedocs/gcc/Developer-Options.html

  1. dump AST info

gcc -fdump-tree-all hello.c

最后更新于