Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't include guards or pragma once working?

Tags:

c++

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?

like image 597
Stewart Avatar asked Nov 24 '09 04:11

Stewart


People also ask

Why pragma once instead of include guards?

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 .

Should you always use pragma once?

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.

Should I use header guards or pragma once?

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.

Is pragma once deprecated?

gcc has pragma once as deprecated. You should use the standard include guards. All pragma directives are by definition implementation defined.


2 Answers

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.

like image 54
James McNellis Avatar answered Oct 12 '22 01:10

James McNellis


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)?

like image 35
Adam Maras Avatar answered Oct 11 '22 23:10

Adam Maras