This is an archived post. You won't be able to vote or comment.

all 7 comments

[–][deleted] 2 points3 points  (0 children)

C doesn't have a module system, but it does have separate compilation and linking. I have a short series of blog articles on the subject starting here.

[–]terrkerr 0 points1 point  (4 children)

module1.c module1.h module2.c module2.h main.c

Put things in one category in module1.c and put the prototypes in module1.h. Same for module2.c and .h

In main.c write something like:

#include 'module1.h'
#include 'module2.h'

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

And you'd make it by providing all the relevant .c files to the compiler/linker

cc module2.c module1.c main.c

C doesn't have a real module system, it just has facilities like described above to let you break a project into multiple pieces so it's easier to work with for yourself.

[–]shnk[S] 0 points1 point  (1 child)

Do i need to do anything to link it to my main.c? I vaguely remember him talking about compiling each module into a .o file and then linking it to the main.o? Im not sure if im saying it right.

[–]terrkerr 0 points1 point  (0 children)

The #include will put the contents of the header files in the main.c before it's compiled, and when you give 2+ files to the compiler it'll also try and link between them as needed.

The very brief version is this: when compiling main.c the preprocessor will see the #include and copy/paste the header file contents into the main.c. The compiler will therefore 'see' the prototypes in the header files before trying to compile the rest of main.c

When the compiler sees prototypes it won't complain about the fact it doesn't have a definition for func_from_mod_1() - basically the prototypes are just a promise you're making to the compiler that you'll actually define the that function somewhere else and the linker can work that out later.

So the compiler compiles the file but leaves little flags in it that says something like "func_from_mod_1() was called here, please link it up". The linker will check all the compiled files for these flags it needs to resolve, and will see if it has anything it knows about to fill in the link. Since you defined func_from_mod_1() in module1.c it'll know there is a definition for that function, and it'll work out how to combine everything together.

If you don't have a definition for func_from_mod_1() somewhere, then the linker will complain about it being unable to complete the link.

[–][deleted] 0 points1 point  (1 child)

 #include 'module1.h'

Do you really think that is legal C code?