I’m a relative beginner to C and I need to learn how makefiles work and I’m a bit confused on how the combination of C files work. Say we have a main.c, a foo.c, and a bar.c. How should the code be written so that main.c recognizes functions in the other files? Also, in foo.c and bar.c, is all of the code written in the main function there or do we need to write other functions for what we need them to do? I’ve read tutorials on how makefiles are written, and it makes sense for the most part, but I’m still a bit confused on the basic logistics of it.
Share
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:
foo.h:
foo.c:
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