0

To check header files with clang-check, it is often suggested to just pass the header to clang-check. However, this does not work well when the header contains a #pragma once guard, because the compiler thinks it is in the main file:

/some/path/foo.h:1:9: warning: #pragma once in main file [-Wpragma-once-outside-header]
#pragma once
        ^

It might seem to be sufficient to disable the warning by adding -Wno-pragma-once-outside-header to compile_flags.txt (or the compilation database), but there may be other errors caused by the compiler ignoring the #pragma once guard in a main file. This is best explained with an example.

Consider the following mini-project structure:

foo.h:

#pragma once

class Foo
{
    Foo();
};

#include "foo.hpp"

foo.hpp:

#pragma once

#include "foo.h"

Foo::Foo()
{
    // do something...
}

compiler_flags.txt:

-xc++

Then running clang-check foo.h leads to these errors:

/some/path/foo.h:1:9: warning: #pragma once in main file [-Wpragma-once-outside-header]
#pragma once
        ^
In file included from ./foo.h:8:
In file included from ./foo.hpp:3:
./foo.h:3:7: error: redefinition of 'Foo'
class Foo
      ^
./foo.hpp:3:10: note: './foo.h' included multiple times, additional include site here
#include "foo.h"
         ^
1 warning and 1 error generated.
Error while processing /some/path/foo.h.

I think the problem could be solved by handling header files differently. An intermediate C++ source file that just includes the given header file could be created and used as an "entry point" for the analysis. Maybe this can be configured somehow?

  • does the same thing happen if you were to define header guards instead of `#pragma once` ? `#ifndef FOO_H #define FOO_H ... #endif ` – NeonFire May 20 '21 at 22:16
  • The dev who implemented `#pragma once` recommends using header guards instead. [link](https://stackoverflow.com/a/34884735/4641116) – Eljay May 20 '21 at 23:15
  • @NeonFire Using include guards instead of `#pragma once` works, but replacing them in a large project where they cause no other problems is not convenient for us. – Jakub Klinkovský May 21 '21 at 07:20
  • @Eljay I don't think a former GCC dev's opinion is relevant for clang. None of the problems discussed in their recommendation applies here. – Jakub Klinkovský May 21 '21 at 07:23

0 Answers0