Multiple source files in C- How exactly do makefiles work?

Generally what will happen is you will define your functions for the other files in a header file, which can then be included in main.c. For example, consider these snippets:

main.c:

#include "foo.h"

int main(int argc, char *argv[]) {
    do_foo();
    return 0;
}

foo.h:

void do_foo();

foo.c:

#include <stdio.h>
#include "foo.h"

void do_foo() {
    printf("foo was done\n");
}

What will happen is that main.c will be turned into an object file (main.o), and foo.c will be turned into an object file (foo.o). Then the linker will link these two files together and that is where the do_foo() function in main.c is ‘associated’ with the function in foo.o.

Example GCC command:
gcc -o myprogram main.c foo.c

Example makefile

myprogam: main.o foo.o
    gcc -o myprogram main.o foo.o

main.o: main.c foo.h
    gcc -c main.c

foo.o: foo.c foo.h
    gcc -c foo.c

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)