Course Content
C Basics
C Basics
Header, Prototypes
Throughout this course, we've consistently utilized the stdio.h
file. This file serves as the standard input/output header.
Contained within it is the prototype for the printf()
function, a function we've employed in every lesson.
Here's an intentional error to illustrate a point:
Main
//#include <stdio.h> int main() { printf("Using `printf()` without `stdio.h`"); return 0; }
Should you exclude the stdio.h
file, the printf()
function will cease to function. Invoking this function without the header will yield an error.
Understanding Header Files
Header files like stdio.h
house declarations of variables, arrays, and function prototypes. They modularize your project code, allowing you to attach components as necessary. This approach streamlines your projects.
Function Prototypes
A function prototype is essentially a function declaration without its actual implementation. Think of a prototype as a "heads-up" to the compiler, signaling the existence of your function.
It resembles a standard function but without the details. Take note of the concluding semicolon (;
). Now, how do we handle a function prototype in a dedicated header file?
Multi-File Projects
Up to this point, we've written our variables and functions in a single file, right alongside the main
function. However, in professional development, this isn't the norm. Let's devise a function to estimate the charge/discharge duration of a capacitor based on its capacitance and resistance.
Our project will be segmented into three files:
func.h
- this will store the function prototype;func.c
- the implementation of our capacitor charge/discharge time calculation function will reside here;main.c
- this primary file will be where all functions are invoked.
Executing this program yields:
Note
%.2f
specifies that the result should be displayed with two decimal places.
Everything was clear?