0

I am new to C and have recently started learning about header files and noticed that a lot of programmers declare functions in .h files

header.h

#ifndef HEADER_H
#define HEADER_H

int func(int a);
int foo(char *s);

And i have noticed that these functions are not defined in the .h files either.

Instead they are defined in a .c file normally in the same directory as the .h file. This seems odd to me and i am a bit confused as to why this occurs.

As far as i know, would it not be okay to define & declare the functions in the .h file and use a header file guard so the function is not #included twice in a program, why define it in a seperate .c file ?

  • 1
    Wrong question. You should ask why anyone doesn't. Although perhaps it's a "no true Scotsman" issue. No true C programmer doesn't. – William Pursell Jul 14 '21 at 11:06
  • That was helpful but what i mainly got from that is that programmers use .h for declaring and .c for defining since it incorporates more modularization and makes the program easier to manage right? – programer21398 Jul 14 '21 at 11:06
  • 1
    That's the *point* of the header file: to make the declaration available to other code modules. It also allows the definition (implementation) to be hidden, for example in a library. – Weather Vane Jul 14 '21 at 11:06
  • @WeatherVane so why not define the functions in the header file along side the declarations? Im guessing because it makes the code harder to manage? – programer21398 Jul 14 '21 at 11:07
  • If you put the definitions in the header file and mask it with a header guard, you are preventing the build system from compiling files individually. The header guard is only useful during the compile step, and there is more to building an executable than compilation. – William Pursell Jul 14 '21 at 11:09
  • Because it wouldn't be a header file? You can include every source file in the main source file if you wish, as a single compilation unit, but that is not the accepted way to do it, and it becomes impossible to have a definition hierarchy in code of any complexity, without having declarations too. – Weather Vane Jul 14 '21 at 11:09
  • If `qux.h` has a header guard and function definitions and `foo.c` and `bar.c` and `main.c` all include `qux.h`, then `cc -c $f.c` will put the definitions in all three object files. When you try to build the executable with `cc foo.o bar.o main.o`, you'll get a multiple definitions. – William Pursell Jul 14 '21 at 11:11
  • @WilliamPursell ahhh ok i get it now that last example really really helped, thank you. – programer21398 Jul 14 '21 at 11:15
  • 1
    Real-world code is broken up into multiple source files - this allows for parallel development, easier code reuse, and incremental builds. By separating declarations into `foo.h` and definitions into `foo.c`, you can compile anything that `#include`s `foo.h` without having to also compile the code in `foo.c`. – John Bode Jul 14 '21 at 14:50

0 Answers0