Thursday, December 9, 2010

Traditional Inclusion Guards vs. #pragma once

Out with the old, in with the "new"...

My professors seem to like traditional inclusion guards as they never even mention the fact that #pragma once exists. I find this to be odd as #pragma once support has quickly ingrained itself into major compilers, including g++, and non-portability is the only reason I could think of for why one wouldn't use it.

Why is #pragma once so great? Take a gander at this wikipedia article. Also, consider the source tree below.

foo/foo.hpp
#ifndef FOO_HPP #define FOO_HPP double func() { return 1.2; } #endif
bar/foo.hpp
#ifndef FOO_HPP #define FOO_HPP double func2() { return 4.3; } #endif
main.cpp
#include <iostream> #include "foo/foo.hpp" #include "bar/foo.hpp" int main() { std::cout << func1(); std::cout << func2(); // Error: func2 is undefined }

Not all that pleasant right? Probably should have used #pragma once instead...

No comments:

Post a Comment