The linker reports duplicate symbol on this:
#ifndef testttt
#define testttt
void anything(){
std::cout<<"hellooooooo";
}
#endif
Because it is inside the include guards, I would expect that this function is only defined once. But apparently not.
I know I can put the word static in front of it and then it will work (which I still find ironic, since static is supposed to give it internal linkage, yet the function can be used from multiple cpp files).
So I guess my two-part question is: 1) Why do the include guards not prevent multiple definitions of this function like they do for other header items, and 2) Why does the static word resolve this when static is supposed to prevent names from visibility in other translation units? I add it, and I can actually call this function from anywhere that includes this header file.
“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
statickeyword 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.