DEV Community

EffessDev for Necoz

Posted on

Why Can't We Just #include "functions.c" in "main.c"? πŸ€”

Explains C preprocessor mechanics for beginners

Suppose we have two files.

functions.c:

#include <stdio.h>

void greet(void) {
  printf("Hi!");
}
Enter fullscreen mode Exit fullscreen mode

main.c:

int main() {
  // Empty
}
Enter fullscreen mode Exit fullscreen mode

And we need to call greet() from main.c. How do we do that? πŸ€”

If you are coming from other languages, you might expect to import functions.c in main.c and call greet().

But C programmers usually create a file named functions.h first, containing the top portion of the function (called declaration):

functions.h:

void greet(void);
Enter fullscreen mode Exit fullscreen mode

Then #include it in main.c and call the function:

main.c:

#include "functions.h"

int main() {
  greet();
}
Enter fullscreen mode Exit fullscreen mode

Why not #include functions.c directly? Why use a header file (functions.h)?

How #include works

The working mechanism of #include "filename" is extremely simple--It just copies that file's contents into that spot before actual compilation begins (literally). main.c would look like this just before compilation:

main.c:

void greet(void); // <-- Contents of functions.h

int main() {
  greet();
}
Enter fullscreen mode Exit fullscreen mode

So functions.h is not strictly needed here, as long as you put void greet(void); (the declaration for the function greet()) in main.c. Like this:

main.c:

void greet(void); // <-- Declaration for greet()

int main() {
  greet();
}
Enter fullscreen mode Exit fullscreen mode

So the question becomes, why we need to declare functions.

Why do we need to declare functions? πŸ€”

When we compile our program, we already specify all source files.

Example build command (using the C compiler gcc):

gcc main.c functions.c -o final_program
Enter fullscreen mode Exit fullscreen mode

Since we already specify all source files here, manual import inside the files (like Python) isn't needed. We do not import source files inside source files, we simply build (compile) them together.

The key part

But each one of those source files compile separately, often in parallel so as to utilise the multiple cores in your CPU. In our case, main.c and functions.c get compiled in parallel. This is the main reason why we need to declare functions.

Lets assume the compiler is compiling this part of main.c:

    greet();
Enter fullscreen mode Exit fullscreen mode

Here, we are calling a function which is not defined in the current file. The compiler doesn't know how to call greet(), like which arguments to pass, the types of the arguments, the return type, etc. Without that info, the compiler wouldn't be able to translate it to machine code

When we add a declaration void greet(void); in main.c, we are promising the compiler that a function named greet that takes no arguments and return nothing exists in one of the source files (note: void means "nothing"). Now, the compiler has our promise so it doens't throw an error saying that this function doesn't exist, as well as the necessary information to compile the calling part. The address to the actual function is left empty.

After compilation, each source file becomes an object file, with the file extension .o (main.o, functions.o).

Then, something called a linker, combines these object files together, giving us the final executable. It will fill in the empty function addresses, and throws an error if the function we promised to exit doesn't exist in any of the source files.

So, that's solved now. But we didn't answer the original question, did we?

Why Can't We Just #include "functions.c in main.c?

We said:

"Each one of those source files compile separately, often in parallel so as to utilise the multiple cores in your CPU."

But if we #include the contents of all files in main.c, main.c would be a single large file before compilation, and we would loose that benefit.

Also, compilers reuse object files. Assume we compiled our project first, then made a few changes to functions.c, and recompiled. The compiler wouldn't compile main.c again to main.o! It detects that main.c wasn't changed, and reuses main.o. If we had #includeed functions.c in main.c, this wouldn't have been possible, since the compiler sees a single, concatenated main.c file.

There is also another problem that happens if you #include "functions.c" in more than one file. Because #include just copies the code in, greet() gets defined more than once across your compiled files, and the linker throws a multiple definition error when combining them.

Putting #pragma once in functions.c wouldn't fix this, because it only stops a file from being included more than once inside the same single file during one compilation. It does not stop if separate .c files #include functions.c and create duplicate definitions for the linker.

Thanks for reading πŸ™‚

This is my first post for Necoz and was inspired by @csm18!


I wrote this entire article from my phone during a bus commute. Feel free to report if there are any typos/issues! 😊

Top comments (18)

Collapse
 
nyaomaru profile image
nyaomaru Necoz •

I've mostly worked with languages that use imports, like TypeScript, Java, Python, and PHP, so learning how C handles separate compilation and linking was really refreshing! 😸

And congratulations on your first Necoz article! I love seeing members inspire each other to write new articles! πŸ’š

Collapse
 
effessdev profile image
EffessDev Necoz •

πŸ™€ Glad you learned something from me :)

Collapse
 
akhourianmolkumar profile image
Akhouri Anmol Kumar Necoz •

Collapse
 
johnclentoira profile image
john Clent Oira •

Really enjoyed this explanation! It's refreshing to see someone explain why C works this way rather than simply telling beginners to use header files and move on.
The distinction between compilation and linking is one of those fundamentals that becomes much more valuable as projects grow.
It also makes me wonder what you think about unity builds, where developers intentionally combine multiple source files to improve compilation performance. At what point do the benefits outweigh the drawbacks of separate compilation?

And writing this entire article on your phone during a bus commute? That's impressive. I can barely write a decent commit message on mine. πŸ˜‚
Looking forward to more articles like this!

Collapse
 
effessdev profile image
EffessDev Necoz •

Thank you so much for the feedback! 😊 When I build an ESP-IDF project, the first compilation is very slow. But subsequent compilations are much faster. I think separate compilation is better during development, since we often update a few files and rebuild? πŸ€”

Collapse
 
akhourianmolkumar profile image
Akhouri Anmol Kumar Necoz •

I'm quite noob in mobile too.

Thread Thread
 
effessdev profile image
EffessDev Necoz •

Everybody's noob on mobile. Particularly on my mobile. Because it only has 4GB RAM. Apps automatically get cleared so there is no multitasking :( If I am writing an article and want to Google something, and I come back to write the article, the entire browser reloads πŸ’€

I tried everything I know to fix this but no wayyy :(

Collapse
 
csm18 profile image
csm Necoz •

Absolutely awesome! You nailed a topic that many beginners struggle with. πŸ”₯

Also, I'm really thankful to you for considering my post an inspiration! 😊

Collapse
 
effessdev profile image
EffessDev Necoz • • Edited

Hehe thanks! πŸ™‚

Collapse
 
csm18 profile image
csm Necoz •

Absolutely!

Thread Thread
 
effessdev profile image
EffessDev Necoz •

Also, your post wasn't the inspiration. YOU were the inspiration (yeah, the post was also inspiration, but you were the first inspiration because the post came after I got inspired :))

Thread Thread
 
csm18 profile image
csm Necoz •

That means a lot to me man! Thank you 🧑

Thread Thread
 
effessdev profile image
EffessDev Necoz •

Thanks! πŸ™‚

Collapse
 
technogamerz profile image
π“π‘πž π‹πšπ³π² 𝐆𝐒𝐫π₯ Necoz •

I was waiting for this!

Collapse
 
effessdev profile image
EffessDev Necoz •

Thanks! I remember you telling me :)

Collapse
 
effessdev profile image
EffessDev Necoz •

Why @xulingfeng why? 😒

I'll write the next article for The Third Cup...

Collapse
 
xulingfeng profile image
xulingfeng Necoz •

πŸ˜…

Collapse
 
the_daily_flare profile image
The daily flare •

I think the parallel compilation point finally made headers click for me.