Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 435
Mochan Avatar asked Jun 12 '19 13:06

Mochan


People also ask

Should all header files have 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.

Where do you put pragma once?

Using #pragma once will delegate the task, of detecting subsequent #include statements for the same file, to the compiler. It can do this efficiently and safely. As a user, there is no room for mistakes. Just place the directive in the first line of every header file.

What is pragma once header file?

#pragma once is a preprocessor directive used to prevent header files from being included multiple times. The #pragma once directive, once present in a file, assures that the file will not be included multiple times in the current project.

Why do I get precompiled headers?

Usage of precompiled headers may significantly reduce compilation time, especially when applied to large header files, header files that include many other header files, or header files that are included in many translation units.


1 Answers

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.

like image 168
Lightness Races in Orbit Avatar answered Oct 04 '22 20:10

Lightness Races in Orbit