Search code examples
c++pragma

Using pragma once in .cpp file


Recently reading some pieces of code I encountered several .cpp files that contained #pragma once in the beginning of file. I know that it is usually used in .h files as guards.

What are the cases when #pragma once should/can/must be used in .cpp files?


Solution

  • #pragma once shouldn't be used in source files, its one goal is to act as include guard. It won't do much harm .cpp files are normally going to be "scanned" once during compilation anyway. Note: Clang tidy will warn you if you do it.

    Warning clang-diagnostic-pragma-once-outside-header #pragma once in main file