0
0
Cprogramming~5 mins

Header and source file organization

Choose your learning style9 modes available
Introduction

We use header and source files to keep code neat and easy to manage. Headers declare what functions and variables are available, and source files contain the actual code.

When your program grows bigger and you want to split code into parts.
When you want to share functions between different files without rewriting them.
When you want to keep your code organized and easy to read.
When you want to avoid repeating code in multiple places.
When you want to make your program easier to fix or update.
Syntax
C
# Header file (example.h)
#ifndef EXAMPLE_H
#define EXAMPLE_H

// Function declarations
void say_hello();

#endif

// Source file (example.c)
#include "example.h"
#include <stdio.h>

void say_hello() {
    printf("Hello!\n");
}

// Main file (main.c)
#include "example.h"

int main() {
    say_hello();
    return 0;
}

Header files usually have .h extension and contain declarations only.

Source files have .c extension and contain the actual code.

Examples
This header file declares a function greet so other files can use it.
C
// example.h
#ifndef EXAMPLE_H
#define EXAMPLE_H

void greet();

#endif
This source file includes the header and defines the greet function.
C
// example.c
#include "example.h"
#include <stdio.h>

void greet() {
    printf("Hi there!\n");
}
The main file includes the header and calls the greet function.
C
// main.c
#include "example.h"

int main() {
    greet();
    return 0;
}
Sample Program

This program uses a header file to declare two functions. The source file defines them, and the main file calls them. This keeps code organized and easy to manage.

C
// greetings.h
#ifndef GREETINGS_H
#define GREETINGS_H

void say_hello();
void say_goodbye();

#endif

// greetings.c
#include "greetings.h"
#include <stdio.h>

void say_hello() {
    printf("Hello!\n");
}

void say_goodbye() {
    printf("Goodbye!\n");
}

// main.c
#include "greetings.h"
#include <stdio.h>

int main() {
    say_hello();
    say_goodbye();
    return 0;
}
OutputSuccess
Important Notes

Always use include guards (#ifndef, #define, #endif) in header files to prevent errors from including the same file multiple times.

Include only what you need in header files to keep them clean and fast to compile.

Keep function definitions in source files, not in headers, to avoid duplicate code errors.

Summary

Header files declare functions and variables for sharing between files.

Source files contain the actual code for those functions.

Organizing code this way makes programs easier to read, reuse, and maintain.