Logo

What is the difference between #include <filename> and #include "filename"?

In C and C++, the #include directive allows you to include the contents of other files (headers) in your source code. Although both #include <filename> and #include "filename" ultimately bring in the specified file, they have different search orders for locating that file:

  1. #include <filename>

    • Typically used for system or standard library headers (e.g., <stdio.h>, <iostream>, <vector>).
    • The preprocessor searches system include paths first. On many systems, this might be something like /usr/include/, /usr/local/include/, or the paths specified by your compiler’s configuration.
  2. #include "filename"

    • Generally used for user-defined or local headers (e.g., "MyClass.h").
    • The preprocessor searches the current directory (or the directory of the source file) first. If it doesn’t find the file there, it then falls back to the same paths used by <filename> (i.e., system include paths).

In practice, the exact search order for both < > and " " is implementation-dependent—meaning different compilers can handle it slightly differently. However, the most common behavior is:

  1. For #include "filename", look in the current/quoted directories (the directory of the source file), then the system include paths.
  2. For #include <filename>, skip the local directory and only look in the system include paths.

Why Two Different Notations?

  1. Clarity of Intent:

    • #include <...> is often used to signal that you’re including a standard library or system header.
    • #include "..." indicates you’re including a local or third-party header that might live alongside your source files.
  2. Avoiding Name Collisions:

    • If you have a local file that has the same name as a standard library header, using the angle brackets (< >) ensures you get the system version first instead of your local version.
  3. Build Configurations:

    • Some build systems might treat the two forms differently by adding additional search paths for local includes, ensuring your project’s header files are found before system headers or external libraries.

Example

#include <iostream> // Likely found in system paths #include "MyHeader.h" // First check current directory, then system paths int main() { std::cout << "Hello world!\n"; return 0; }
  • <iostream> is part of the C++ standard library.
  • "MyHeader.h" might be a header you’ve created in your project’s source directory.

Takeaway

  • Use #include <filename> for standard library or system headers.
  • Use #include "filename" for headers located in your local project directories.
  • The difference mainly involves where the compiler looks first to find the file, which helps avoid naming collisions and clarifies the distinction between system libraries and project-specific code.

Recommended Resources

CONTRIBUTOR
TechGrind