I'm compiling some code that relies on include guards to prevent multiple definitions of objects and functions, but Visual Studio 2008 is giving me link errors that there are multiple definitions. I don't understand why because I've used code very similar to this before and it hasn't caused problems. I must be doing something dumb but I have no idea what it is. I also tried to take out the include guards and use #pragma once, but I get the same link errors. What should I check for?
In the absence of #include guards around #include directives, the use of #pragma once will improve compilation speed for some compilers since it is a higher-level mechanism; the compiler itself can compare filenames or inodes without having to invoke the C preprocessor to scan the header for #ifndef and #endif .
Be careful not to use #pragma once or the include guard idiom in header files designed to be included multiple times, that use preprocessor symbols to control their effects. For an example of this design, see the <assert. h> header file.
In addition to reducing errors, #pragma once is typically optimized to reduce the use of the preprocessor and file openings, making it faster than include guards. Note that many compilers optimize for this already, so it is possible they are equally fast.
gcc has pragma once as deprecated. You should use the standard include guards. All pragma directives are by definition implementation defined.
If they are linker errors, the most likely cause is probably non-inline functions defined in the header.
If you have a non-inline function in a header that is included in more than one source file, it will be defined in each of those source files ("translation units"), thus the function will be defined more than once, hence the multiple definitions error.
If you're getting linker errors... are you sure you're not 1) actually defining a function twice in code or 2) trying to do something silly like #include
a source file (as opposed to a header file)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With