Compiling Multiple Files

You may or may not have noticed that you can make multple C files and compile them into one output ex:


main.c

#include <stdio.h>


void print();


int main(int argc, char *argv[]) {

print();

return 0;

}


functions.c

#include <stdio.h>


void print() {

printf("Whaa! Printing from a differnt file!");

}


You could compile it like this:

gcc -o test main.c functions.c


Then execute it like so:

./test


But even this is a bit strange, why would I prototype a function in one file and write it in another? Answer: Header files! (Note the .h extention just like our stdio.h bro!)


header.h

void print();


Now lets change our main program to include this header and remove the prototype.


functions.c

#include <stdio.h>

#include
"header.h"


int main(int argc, char *argv[]) {

print();

return 0;

}


This will compile and execute the same way and it will be smart enough to look for a file called header.h to include!



So now we have three seperate files:


main.c

The driver holding the main function.

functions.c

The Function's logic

header.h

The header file containing the function prototypes.


Thease are all getting compiled into one executable.

test


As you can imagen this is very useful for large programs.

People can independantly make their own libraries.

Then compile it into a final output.


Some notes:

1) You can only have one main() function out of all the files.

2) You can have as many function files as you would like.

3) The files should have some logical grouping to them.

4) You will only need to #include files relevent to the current file.