c++
#include
filename

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

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

The difference between #include <filename> and #include "filename" in C and C++ lies in how the compiler searches for the included file.


1. #include <filename>

  • Purpose: Typically used for including standard library headers or system headers.
  • Search Path: The compiler searches for the file in the standard system include paths (e.g., paths specified by the environment or the compiler installation).
  • Example:
cpp
  #include <iostream>

This tells the compiler to look for iostream in the system include directories.


2. #include "filename"

  • Purpose: Typically used for including user-defined headers or headers in your project.
  • Search Path:
    1. The compiler first searches for the file in the directory of the file being compiled (or a specified relative path).
    2. If not found, it then searches in the standard system include paths.
  • Example:
cpp
  #include "my_header.h"

This tells the compiler to first look for my_header.h in the current directory.


Practical Differences

  • Custom Headers: Use #include "filename" for headers you create as part of your project, as it ensures the compiler looks in the current directory first.
  • System Headers: Use #include <filename> for standard headers, as it directs the compiler to only search the system include paths.

Customization of Search Paths

You can control where the compiler looks for headers using compiler flags:

  • Include Directories:
bash
  g++ -I/path/to/custom/include -o program main.cpp

This adds /path/to/custom/include to the search paths for both #include <filename> and #include "filename".

  • Order of Search: For #include "filename", the compiler always checks the current directory first before searching include paths.

Summary

DirectiveSearch PathUse Case
#include <filename>Standard system include pathsStandard library or system headers
#include "filename"Current directory, then standard system pathsProject-specific or custom headers

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.