Print Default Include Directories using gcc or g++ Compiler

Print Default Include Directories using gcc or g++ Compiler

When compiling C or C++ code, the compiler needs to locate the header files referenced in the source files using #include directives. These headers can come from the standard library, third-party packages, or custom code. To find headers, the compiler searches through a predefined list of directories, known as default include paths. This tutorial demonstrates how to print default include directories using gcc or g++ compiler.

Here is how we can print default include directories:

gcc -Wp,-v -E - < /dev/null 2>&1 | sed -n 's/^ //p'
g++ -Wp,-v -E -x c++ - < /dev/null 2>&1 | sed -n 's/^ //p'
  • -Wp,-v - passes the -v flag to the preprocessor. The -v option on its own (when passed to the compiler) shows verbose information about the overall compilation process. But when passed specifically to the preprocessor, it outputs the list of include directories that the preprocessor searches by default.
  • -E - run only the preprocessor stage (no compilation or linking).
  • - - the hyphen instructs the compiler to read input from standard input (stdin) rather than a source file, working in conjunction with the rest of the command part to avoid compiling an actual file.
  • < /dev/null - this sends an empty input stream to the compiler, causing it to process a blank file with no actual code.
  • 2>&1 - redirects stderr (where -v outputs its data) to stdout.
  • sed -n 's/^ //p' - filters and prints only the indented lines (the actual include paths).
  • -x c++ - this instructs the compiler to treat the input as C++ code, even though no actual file is provided. It's necessary because we're redirecting an empty stream, and the option ensures the compiler recognizes the input as C++ source.

You might see something like this:

/usr/lib/gcc/x86_64-linux-gnu/11/include
/usr/include/x86_64-linux-gnu
/usr/include

Leave a Comment

Cancel reply

Your email address will not be published.