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.
Header and source file organization
# 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.
greet so other files can use it.// example.h #ifndef EXAMPLE_H #define EXAMPLE_H void greet(); #endif
greet function.// example.c #include "example.h" #include <stdio.h> void greet() { printf("Hi there!\n"); }
greet function.// main.c #include "example.h" int main() { greet(); return 0; }
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.
// 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; }
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.
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.