GCC (GNU Compiler Collection) is a powerful and widely-used compiler suite for various programming languages. This cheat sheet provides essential commands and options to compile and manage code efficiently using GCC.

Introduction:

GCC supports several programming languages, including C, C++, and Fortran. It is a crucial tool for developers, providing a range of options to control compilation, optimization, and output.

Compiling C Programs:

CommandDescription
gcc [source_file.c] -o [output_executable]Compile a C program and generate an executable.
gcc -c [source_file.c]Generate object files without linking.
gcc -Wall [source_file.c] -o [output_executable]Enable most warning messages during compilation.

Compiling C++ Programs:

CommandDescription
g++ [source_file.cpp] -o [output_executable]Compile a C++ program and generate an executable.
g++ -c [source_file.cpp]Generate object files without linking.
g++ -Wall [source_file.cpp] -o [output_executable]Enable most warning messages during compilation.

Linking and Libraries:

CommandDescription
gcc [source_file.c] -o [output_executable] -l[library_name]Link with a specific library during compilation.
gcc -L[path_to_library] -l[library_name]Specify the library path during compilation.
ldd [output_executable]Display shared library dependencies.

Optimization:

CommandDescription
gcc -O[level] [source_file.c] -o [output_executable]Set the optimization level (0, 1, 2, 3).
gcc -march=native [source_file.c] -o [output_executable]Optimize for the host machine’s architecture.

Debugging:

CommandDescription
gcc -g [source_file.c] -o [output_executable]Generate debugging information.
gdb [output_executable]Start the GNU Debugger for debugging.

Preprocessor Directives:

CommandDescription
gcc -E [source_file.c]Run only the preprocessor and output the result.
gcc -D[macro_name] [source_file.c] -o [output_executable]Define a macro during compilation.

Miscellaneous:

CommandDescription
gcc -vDisplay the version and configuration of GCC.
gcc -print-search-dirsPrint the default directories used by GCC.
gcc -H [source_file.c]Display include file hierarchy during compilation.

Conclusion

This GCC compiler cheat sheet provides a handy reference for developers working with C, C++, and Fortran code. Whether you are compiling, linking, optimizing, or debugging, GCC offers a multitude of options to suit your needs. Use this cheat sheet to streamline your compilation process and enhance your understanding of GCC’s capabilities.