0
0
CHow-ToBeginner · 3 min read

How to Use #include in C: Syntax and Examples

In C, use the #include directive to insert the contents of a header file into your source file before compilation. Use #include <filename> for standard library headers and #include "filename" for your own files.
📐

Syntax

The #include directive tells the compiler to copy the contents of a specified file into the current file. There are two common forms:

  • #include <filename>: Includes standard library headers or system files.
  • #include "filename": Includes user-defined or local header files.

The angle brackets tell the compiler to look in system directories, while quotes tell it to look in the current directory first.

c
#include <stdio.h>
#include "myheader.h"
💻

Example

This example shows how to include the standard stdio.h header to use the printf function.

c
#include <stdio.h>

int main() {
    printf("Hello, world!\n");
    return 0;
}
Output
Hello, world!
⚠️

Common Pitfalls

Common mistakes when using #include include:

  • Using quotes instead of angle brackets for standard headers, which may cause the compiler to not find the file.
  • Forgetting to use header guards in your own header files, causing multiple inclusion errors.
  • Including the same header multiple times without guards, leading to redefinition errors.
c
#ifndef MYHEADER_H
#define MYHEADER_H

// Your declarations here

#endif

// Wrong: Missing header guards can cause errors
#include "myheader.h"
#include "myheader.h"
📊

Quick Reference

Remember these tips when using #include:

  • Use <> for system headers.
  • Use "" for your own headers.
  • Always add header guards in your header files.
  • Place #include at the top of your source files.

Key Takeaways

Use #include <filename> for standard library headers and #include "filename" for your own files.
The #include directive copies the contents of the specified file into your source before compiling.
Always use header guards in your own header files to prevent multiple inclusion errors.
Place #include directives at the top of your C source files for clarity and correctness.