Mochan
Mochan

Reputation: 1379

gcc precompiled header: pragma once in main file

I created a header file. Something simple as follows.

#pragma once

#include <iostream>

template<typename T>
void say(T t) {
    std::cout << t << std::endl;
}

and then use g++ to create the gch pre-compiled header with g++ hello.h. It gives me this warning ->

pch.h:2:9: warning: #pragma once in main file
    2 | #pragma once
      |         ^~~~

But the gch file created and the pre-compiled header works fine. This error goes away if I use header guards.

Am I doing something wrong here?

Upvotes: 15

Views: 5560

Answers (3)

Florian Weimer
Florian Weimer

Reputation: 33757

This is a known GCC bug:

To my knowledge, there is no good way to disable this warning. One way that retains matching behavior is an additional indirection. In pch.h, use

#include <pch-real.h>

(without #pragma once), and store the actual header contains in pch-real.h. This mostly preserves the include-only-once optimization even if <pch.h> is included multiple times in non-PCH mode.

Upvotes: 2

Johan Boul&#233;
Johan Boul&#233;

Reputation: 2089

The main source file used to generate a precompiled header is usually a made-up "indirect" header that contains only a bunch of #include for all the actual real headers you want to precompile. When you use the machinery this way, there is no need for a #pragma once (nor guard) in the main file, and hence it works as intended with no warning.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

You're not doing anything wrong; this is a quality of implementation issue that has been mentioned on the issue tracker before (but, to my knowledge, there are currently no plans to change the behaviour).

In Clang, you could turn off the warning for that particular compiler invocation (with -Wno-pragma-once-outside-header); in GCC you'll just have to grin and bear it for now.

Upvotes: 10

Related Questions