https://gcc.gnu.org/bugzilla/show_bug.cgi?id=110092

--- Comment #5 from Piotr Nycz <piotrwn1 at gmail dot com> ---
(In reply to Jonathan Wakely from comment #2)
> (In reply to Piotr Nycz from comment #0)
> > So, probably it is doable to add warning like: "bist/shared_ptr.h is an
> > internal header file, included by other library headers. Do not attempt to
> > use it directly. Use <memory> instead"
> 
> We could add this to <bits/shared_ptr.h>:
> 
> #ifndef _GLIBCXX_MEMORY
> # error Do not include <bits/shared_ptr.h> directly, include <memory>
> instead.
> #endif
> 
> But then you'd get an error when you include <regex>, or <filesystem>, or
> <chrono>, or any of the other headers that use std::shared_ptr internally.
> 
> So we'd have to do:
> 
> #if !defined _GLIBCXX_MEMORY && !defined _GLIBCXX_CHRONO && !defined
> _GLIBCXX_REGEX \
>     && ! defined ...
> 
> And that would be a pain to maintain.
> 
> And then it would still not give an error for this, even though it's still
> wrong:
> 
> #include <chrono>
> #include <bits/shared_ptr.h>
> std::shared_ptr<int> p;
> 
> So I don't think this can really be solved in the compiler without a lot of
> work to hardcode special handling for each of those headers.

After few days this problem was sitting in my head - I think I found easy
solution to std library and all other libs with similar problems of how to
prevent users from including internal headers.

1. Define at the beginning of each interface header some macro/symbol, undef it
at the end of each file.
2. In every internal header - make sure this symbol is defined, otherwise
#error (I would prefer #warning in this case - just in case somebody do include
this internal header already for some reasons)

An example:

```
//@file memory

#ifndef GCC_STD_LIBRARY_HEADER
#define GCC_STD_LIBRARY_HEADER 1
#else
#define GCC_STD_LIBRARY_MEMORY_HEADER_IS_NOT_FRONT_HEADER 1
#endif

...
#include <bits/shared_ptr.h>

...

#ifdef GCC_STD_LIBRARY_MEMORY_HEADER_IS_NOT_FRONT_HEADER
#undef GCC_STD_LIBRARY_MEMORY_HEADER_IS_NOT_FRONT_HEADER
#else
#undef GCC_STD_LIBRARY_HEADER
#endif


```

```
//@file bits/shared_ptr.h

#if !defined(GCC_STD_LIBRARY_HEADER) &&
!defined(I_KNOW_INCLUDING_BITS_SHARED_PTR_H_IS_NOT_SUPPORTED_BY_STDLIB_BUT_I_NEED_TO_DO_IT)
#warning bits/shared_ptr.h is ... internal ..., include <memory> instead"
#endif

...

```

Reply via email to