C supports a concept known as encapsulation, which means the user of a piece of code doesn't (and should by no means) need to know how it is implemented to use it.
The header (.h) file contains what other languages call the interface or specification (what it does and how to use it) of the piece of code, and the C source (.c) contains its implementation (how it actually does its job).
In a header file, you'll find declarations, e.g. void printUsage();
and in a C source, you'll find definitions, e.g.
void printUsage() {
puts("Usage: mycommand [options] someArg...\n");
}
Most of the time, C source files contain more definitions than declaration, which means users of a functionality manipulate only a subset of the code needed to implement it. Other languages have more precise ways of defining the visibility of a piece of code. Those languages would call functions and variables declared in the header file "public" and those only declared in the C source file (hence invisible outside) "private".
When you write a C program, you'll need to use things defined elsewhere, so you'll have to include their interface at the beginning of your C source and link your program with their implementation.
myprogram.c
#include <mylib.h>
int main(int argc, char *argv[]) {
myfunction_from_mylib();
}
To compile it, you'll have to type: cc -lmylib -o myprogram myprogram.c
See the man page of cc
for more information, in particular the -l, -o, -I and -L
options.
The angle brackets in #include search for the included header file in the directories specified by the -I
option.
If you use double quotes instead of angle brackets, the included file path will be relative to the location of your C source file.
Note the main()
function is special: it is the entry point of your program, i.e. the first piece of code to be executed when your program starts.
The main function can be defined in one of 2 ways: int main()
if you don't need to use command line arguments, and int main(int argc, char *argv[])
if you do. Any other declaration is illegal.
Makefiles are entirely different things, they describe how to build a complex application, which may or may not be written in C. See the man page of the make
command for more information. I think it would be worth opening a different thread about it to avoid mixing unrelated things.
For your first steps, you can use the cc command manually to compile and link your application so as to learn only one thing at a time. You'll need to use make and a Makefile when your program will grow to a point that splitting it in several source files will become an obvious thing to do.