There was a push to make pragma once standard... I think it died out though.
I'll tell you what each different solution does, and why the #ifndef is not a complete solution for this problem.
First, only .cpp files are compiled, and thus only headers included from a .cpp file are compiled; this chain of files is called a
translation unit . Essentially, each .cpp in your program creates and/or belongs to a translation unit (when it is compiled).
Doing what you are doing will manifest trouble in two different ways, but for essentially the same reason; duplicate definition. If you include the same header multiple times in the same translation unit the compiler thinks you declared two different functions, but accidentally gave them the same name, and emits an error. The #ifndef method will fix this problem (because it make s certain a header is only included once in that translation unit).
However it's not completely solved yet, because you could include that function in two different translation units. Everything will compile, however when the compiled code is linked together, the linker will find duplicated function(s) and emit an error.
To solve this problem, you somehow need to tell the compiler it's the same function.
The traditional method is to declare the function 'extern' (i.e. global) and separate the function declaration (goes in the header file,.hpp, e.g. extern int MyFunc(int); ) from the definition (goes in the source file, .cpp, e.g. int MyFunc(int i) {return i+1;} ). Sometimes that's alot of trouble for one simple function, and templates cannot be compiled in source files.
The remaining two options are to declare the function either inline or static.
Declaring the function inline has the compiler to do two things; ignore duplicate definitions that are the same, and try to avoid actually making a function call - instead it will 'inline' the code right where it is invoked (kinda like a #define macro).
Declaring the function static tells the compiler that you what this function to exist on-it's-own in each translation unit. You effectively get a separate copy of the function in each translation unit. If you use static variables inside of the function, and declare the function static, each translation unit will get it's own static variables. This is different than declaring it extern (or inline), then all translation units would share the same static variables.
- Magmai Kai Holmlor
"No, his mind is not for rent to any god nor government" - Rush, Tom Sawyer
[Look for information |
GDNet Start Here |
GDNet Search Tool |
GDNet FAQ |
MSDN RTF[L] |
SGI STL Docs |
STFW |
Asking Smart Questions ]
[Free C++ Libraries |
Boost |
ACE |
Loki |
MTL |
Blitz++ |
wxWindows|
Spirit(xBNF)]
[Free C Libraries |
zlib ]
[edited by - Magmai Kai Holmlor on August 13, 2003 10:54:16 PM]
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara