Does the #pragma once apply to a single include file or to everything?

UPDATE : Understood, it spreads to the file itself. Then why, when I specified #pragma once in the file and try to connect it to other (several) files, I get linking errors:

 1>error LNK2005: "void __cdecl logit(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,int,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?logit@@YAXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H0@Z) already defined in file2.obj 1>error LNK2005: "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl GetTime(void)" (?GetTime@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) already defined in file2.obj 1>error LNK2005: "void __cdecl GetDate(void)" (?GetDate@@YAXXZ) already defined in file2.obj 1>fatal error LNK1169: one or more multiply defined symbols found 

    2 answers 2

    You misunderstand this directive. It applies to the file in which it is defined.

    That is, it needs to be added to .h files (those that are connected using #include ) to the very top. It is "equivalent" to the next, rather popular design.

     #ifndef _GUARD_H_ #define _GUARD_H_ //код #endif 

    But the problem is observed because your h file gets into many different cpp files. And of course, the linker detects many of the same functions and swears. Treat it like this. Either simply add inline to the definition of the function at the very beginning (but this is ugly, especially if the functions are not small), or create a separate cpp file, put the body of each function there, and leave only the prototypes in the h file. This is the right, good way. But if your functions in the h file occupy one or two lines, then it is possible through inline.

    • Well, lines of 20, but a lot of them ... Now I will try, thank you - Dmitry

    As I recall, it applies to the current file, i.e. must be in the header file, not outside it. So place it in all your included files ...

    To update

    Your problem is related to the fact that there are a lot of ads , but the definition is only one. Apparently, you place the definition of the function in the header file, and as a result, there is a corresponding code in each object file. And the linker is not able to understand what to choose.

    Place in the header files only ads. The function - without a body, with a body - is only template and inline (you can still static or in an anonymous namespace, but this will not give what you really want - the functions will simply be duplicated), the variables - only extern .