Why include guards do not prevent multiple function definitions? [duplicate]

“1) Why do the include guards not prevent multiple definitions of this function like they do for other header items”

Because each translation unit (i.e. .cpp file) is processed separately and goes through the same conditional. Translation units won’t share the preprocessor definitions encountered by other translation units. This means that all the translation units that will process that header will include a definition for that function. Of course, the linker will then complain that the same function has multiple definitions.

“2) Why does the static word resolve this when static is supposed to prevent names from visibility in other translation units?”

Because the static keyword makes a private copy of that function for each translation unit.

If you want that function to be defined in a shared header, however, you should rather mark it as inline, which will solve your problem and will make the preprocessor guards unnecessary.

Leave a Comment