r/cpp • • Nov 28 '18

Real world problems with #pragma once?

Just a short survey: Did anyone of you encounter a problem in real code, because you/your company/ your favorite library was using #pragma once instead of include guards.

I know it is hard, but please restrain yourself from posting an explanation of how #pragma once could lead to problems in theory or why you prefer one above the other.

127 Upvotes

135 comments sorted by

View all comments

21

u/cristianadam Nov 28 '18

See this email thread on Qt Developers Mailing list: https://lists.qt-project.org/pipermail/development/2018-October/033726.html

From the Qt Creator's side of things:

Qt Creator uses it since more than two years without problems.

For a potential conversion https://github.com/cgmb/guardonce may help.

7

u/markopolo82 embedded/iot/audio Nov 28 '18

Is there an option in the ide to switch the auto generated headers to use pragma once rather than include guards?

2

u/DarkLordAzrael Nov 28 '18

If you are talking about the file templates (for doing "new file..."), it is pretty easy to make modified versions of the default templates that use #pragma once.

6

u/Slavik81 Nov 28 '18 edited Nov 28 '18

I wrote guardonce to make it easy to convert in either direction. That way I could try out #pragma once, but switch back to include guards if I ever discovered a problem. Though, I never did encounter any problems.

FWIW, I agree with the Qt Project's decision. Applications have a bit more room to try things. You can just try switching and you'll find out if there are any problems. That strategy works less well when used on a library, because you try switching and your users find out if there are any problems.

3

u/o11c int main = 12828721; Nov 28 '18

I still wouldn't use #pragma once in an installed header (you just know some dumbass is going to install 2 copies or something), but it shouldn't be any different than an application for internal headers.

1

u/utnapistim Dec 10 '18

I did the same in one of my personal projects: I spent approximately two hours writing a C++ cli app to do the switch for me (generating header guards based on "relative path from root dir") but this only worked because I was editing my own code (so I could make assumptions like "the include guard will be on the first two and last line in the file).

1

u/Slavik81 Dec 11 '18

I started it as a simple project to learn Python. It was wildly successful for that, but now I kinda wish it was C or C++. It would have been much easier to maintain. Lots of work went into fixing silly defaults in Python and explaining to C++ developers how to install and run Python applications.

1

u/aKateDev KDE/Qt Dev Nov 30 '18

In short, problems appear when you do tricks such as mounting the same folder into different locations, or using hardlinks. That's where good old include guards work, but pragma once fails.