How can I split up my monolithic programs into smaller, separate files?

c

Solution

Well, that's exactly what you want : split your code in several libraries !

Let's take an example, in one file you have :

#include <stdio.h>

int something() {
    return 42;
}

int bar() {
    return something();
}

void foo(int i) {
    printf("do something with %d\n", i);
}

int main() {
    foo(bar());
    return 0;
}

you can split this up to :

mylib.h:

#ifndef __MYLIB_H__
#define __MYLIB_H__

#include <stdio.h>

int bar();
void foo();

#endif

N.B.: the preprocessor code above is called a "guard" which is used to not run twice this header file, so you can call the same include at several places, and have no compilation error

mylib.c:

#include <mylib.h>

int something() {
    return 42;
}

int bar() {
    return something();
}

void foo(int i) {
    printf("do something with %d\n", i);
}

myprog.c:

#include <mylib.h>
int main() {
    foo(bar());
    return 0;
}

to compile it you do :

gcc -c mylib.c -I./
gcc -o myprog myprog.c -I./ mylib.o

now the advantages ?

- it enables you to split logically your code, and then find the code unit faster

- it enables you to split your compilation, and recompile only what you need when you modified something (which is what the Makefile does for you)

- it enables you to expose some functions and hide others (like the "something()" in the example above), and it helps documenting your APIs for people that will read your code (like your teacher) ;)

Problem

In all the code I see online, programs are always broken up into many smaller files. For all of my projects for school though, I've gotten by by just having one gigantic C source file that contains all of structs and functions I use. What I want to learn how to do is split my program up into smaller files, which seems to be the standard professionally. (Why is this, by the way -- is it just for ease of reading?) I've searched around, and all I can find information on is building libraries, which isn't what I want to do I don't think. I wish I could be more helpful, but I'm not totally sure about how to implement this -- I'm only sure about the end product I want.

Original source