Why aren't my compile guards preventing multiple definition inclusions? Why aren't my compile guards preventing multiple definition inclusions? c c

Why aren't my compile guards preventing multiple definition inclusions?


If the linker is complaining, it means you have definitions rather than just declarations in your header. Here's an example of things that would be wrong.

#ifndef X_H#define X_Hint myFunc(){  return 42; // Wrong! definition in header.}int myVar; // Wrong! definition in header.#endif

You should split this into source and header file like this:

Header:

#ifndef X_H#define X_Hextern int myFunc();extern int myVar; #endif

C Source:

int myFunc(){  return 42; }int myVar; 


Header guards are only good for a single compilation unit, i.e., source file. If you happen to include a header file multiple times, perhaps because all headers included from main.c in turn include stdio.h then guards will help.

If you have the definition of a function f in x.h which is included by main.c and util.c, then it is like copying and pasting the definition of f into main.c when creating main.o and doing the same for util.c to create util.o. Then the linker will complain and this happens despite your header guards. Having multiple #include "x.h" statements in main.c is possible of course because of these guards.


Using include guards prevents one compilation unit from including the header twice. E.g. if header B.h includes A.h and B.cpp includes A.h and B.h, everything from A.h would be declared twice in the compilation B.cpp if you weren't using include guards.

Your include guards prevent this from happening, all's fine till now.

But you get multiple definitions at link time, i.e. two compilation units define the same thing, this probably means you got a real definition in your header, use extern for all variables, make sure functions are either inline or are defined in the cpp file.