CodeBlanks Logo Icon CodeBlanks

Headers and sources

  • C course
  • Intermediate
  • Lesson 59/116
  • 5 min

Learn the difference between .h and .c files.

Headers and sources

C projects split into two file types: headers (.h) and sources (.c). Headers carry function declarations and type definitions; sources contain function definitions. Another .c file includes the header with #include and calls the declared functions.

Example: math_utils.h has int add(int, int); declaration, math_utils.c has int add(int a, int b) { return a + b; } definition. This split cuts compile time in big projects and gives modularity; each module ships with its own header.

Include guard

When a header is included multiple times, double declaration errors arise. To prevent this, use an include guard: #ifndef MATH_UTILS_H, #define MATH_UTILS_H, content, #endif.

On first include MATH_UTILS_H is undefined; #ifndef is true, the macro is defined and content is processed. On second include the macro is defined; #ifndef is false and content is skipped. Modern C also uses #pragma once; shorter but compiler-specific. Include guards are standard and portable.

Practice Write header and main

Simulate in one file: #ifndef MATH_H, #define MATH_H, the declaration int add(int, int);, #endif. Then the definition int add(int a, int b) { return a + b; }. In int main(void) add printf("%d\n", add(3, 4));. Don't forget <stdio.h>.

Starter code

main.c
#include <stdio.h>

// Start MATH_H include guard
// Declare add
// Close guard

// Define add

int main(void) {
    // Call add(3, 4) and print
    return 0;
}

Sample solution

main.c
#include <stdio.h>

#ifndef MATH_H
#define MATH_H
int add(int, int);
#endif

int add(int a, int b) {
    return a + b;
}

int main(void) {
    printf("%d\n", add(3, 4));
    return 0;
}

Expected output

7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Where does a function definition live?

  • Only in .c Correct answer
  • Only in .h
  • In both .h and .c
  • In the Makefile

Explanation: The definition is in .c; the declaration is in .h.

2 Complete the include guard macro

Question
#ifndef UTILS_H
#____ UTILS_H
int util_add(int, int);
#endif
Answer
#ifndef UTILS_H
#define UTILS_H
int util_add(int, int);
#endif

Explanation: #define UTILS_H defines the macro and prevents re-inclusion.

3 Match file types to their content

Term Meaning
math_utils.h Declarations
math_utils.c Definitions
main.c Program entry
Makefile Build recipes

All lessons in Intermediate