.c)
files.
What is a Function Declaration?
A function declaration tells the compiler the function's name, return type, and parameters. It informs the compiler that the function exists somewhere else in the program.
int add(int a, int b);
The above statement is only a declaration. It does not contain the implementation of the function.
What is a Function Definition?
A function definition contains the actual code that performs the required task.
int add(int a, int b)
{
return a + b;
}
The above code is the definition because it includes the
function body enclosed within braces { }.
Typical Project Structure
project/
│── math.h // Function declarations
│── math.c // Function definitions
│── main.c // Uses the functions
math.h
#ifndef MATH_H
#define MATH_H
int add(int a, int b);
#endif
math.c
#include "math.h"
int add(int a, int b)
{
return a + b;
}
main.c
#include
#include "math.h"
int main()
{
printf("%d", add(10, 20));
return 0;
}
Output
30
Declaration vs Definition
| Feature | Function Declaration | Function Definition |
|---|---|---|
| Purpose | Tells the compiler about the function. | Provides the implementation of the function. |
| Contains Function Body | No | Yes |
| Ends With | Semicolon (;) | Curly braces { } |
| Usually Stored In | Header (.h) file | Source (.c) file |
| Can Be Repeated | Yes | No (only one definition) |
Why Don't We Usually Define Functions in Header Files?
Problems
- Multiple definition errors during linking.
- Larger executable size.
- Difficult code maintenance.
- Violation of modular programming principles.
Best Practice
- Place declarations in
.hfiles. - Place definitions in
.cfiles. - Include header files wherever required.
- Use include guards to prevent duplicate inclusion.
Exception
Small functions can sometimes be defined inside header files using the
inline keyword. This allows the compiler to expand the function
directly at the point of the call, which may improve performance.
static inline int square(int x)
{
return x * x;
}
Prerequisites
- Basic knowledge of C functions.
- Understanding of header (
.h) and source (.c) files. - Knowledge of
#includedirectives. - Basic understanding of modular programming.
Key Takeaway
In C programming, header files normally contain function declarations (prototypes), while the actual function definitions are written in source (.c) files. This separation improves modularity, code reuse, and maintainability while preventing multiple definition errors.