0
0
Cprogramming~30 mins

Header and source file organization - Mini Project: Build & Apply

Choose your learning style9 modes available
Header and source file organization
📖 Scenario: You are creating a simple C program that calculates the area of a rectangle. To keep your code clean and organized, you will separate the function declaration and definition into a header file and a source file.
🎯 Goal: Build a C program that uses a header file to declare a function and a source file to define it, then call the function from main.c to calculate and print the area of a rectangle.
📋 What You'll Learn
Create a header file rectangle.h with a function prototype for int area(int width, int height);
Create a source file rectangle.c that includes rectangle.h and defines the area function
Create a main.c file that includes rectangle.h, calls area with width 5 and height 10, and prints the result
Use proper include guards in the header file
💡 Why This Matters
🌍 Real World
Organizing code into header and source files is a common practice in C programming to keep code clean, reusable, and easier to maintain.
💼 Career
Understanding how to separate declarations and definitions and compile multiple files is essential for working on real-world C projects and collaborating with other developers.
Progress0 / 4 steps
1
Create the header file with function prototype
Create a header file named rectangle.h. Inside it, write include guards using #ifndef RECTANGLE_H, #define RECTANGLE_H, and #endif. Between the guards, declare the function prototype int area(int width, int height);.
C
Need a hint?

Include guards prevent the header file from being included multiple times. The function prototype tells the compiler about the function's name, return type, and parameters.

2
Define the area function in the source file
Create a source file named rectangle.c. Include the header file rectangle.h at the top. Define the function int area(int width, int height) that returns the product of width and height.
C
Need a hint?

Include the header file with double quotes. The function should multiply width and height and return the result.

3
Write the main program to use the area function
Create a source file named main.c. Include the header file rectangle.h. In the main function, call area with arguments 5 and 10, store the result in an int variable named result, and then print "Area: " followed by the result using printf.
C
Need a hint?

Remember to include stdio.h for printf. The main function should return 0.

4
Compile and run the program to see the output
Compile the program files main.c and rectangle.c together and run the executable. The program should print Area: 50.
C
Need a hint?

Use a command like gcc main.c rectangle.c -o program to compile, then run ./program to see the output.