3

A lot of the C++ code that I write on my mac do not compile when ported over to a machine that compiles with gcc for the reason that I didn't include the libraries.

For example, the following code compiles on with Clang even though I did not #include <memory>, but does not compile in gcc. I assume it compiles in Clang because the iostream explicitly/implicitly includes memory? If so, why are the libraries set up differently between different compilers instead of having some conventional standard that's ubiquitous? I find Clang to be a lot more lax than g++, and I don't think it's beneficial because code is not immediately portable.

#include<iostream>

int main() 
{ 
  std::unique_ptr<int> d;
}

24n8
  • 1,898
  • 1
  • 12
  • 25
  • 7
    It is completely up to the implementation what headers they include within other headers. That is why, especially when targeting different compilers, you should always include what you use, even if it "accidentally" compiles without the right headers. – Cory Kramer Apr 22 '20 at 15:25
  • 5
    My advice in addition to the advice of the first comment is if you are gong to support other compilers you should regularly test on other compilers while you develop your code. – drescherjm Apr 22 '20 at 15:29
  • the dupe is about `` but the answer is the same – 463035818_is_not_an_ai Apr 22 '20 at 15:43
  • 2
    A header might or might not include additional other headers. And which headers are included might change from version to version of the library or in case of the std for different implementation. So whenever you need a certain data type in your file you should either add the include for the header that directly provides this type or add a forward declaration if you don't only need the declaration. – t.niese Apr 22 '20 at 15:43
  • @CoryKramer. Right, I guess because I do most of my development work on a mac, I've gotten kind of lazy with including headers because I don't run into compiling issues. I assume there's no way to make clang more strict so that it reminds me to include headers explicitly? – 24n8 Apr 22 '20 at 15:45
  • 2
    @Iamanon you could include a tool like [include-what-you-use](https://include-what-you-use.org/) which will warn you about missing headers and/or tells you if a forward declaration would be sufficient. For certain libraries - glm for example - it might give you false suggestions, but in most cases it works. – t.niese Apr 22 '20 at 15:46

0 Answers0